@data-loom/auth-js 0.0.2-alpha.2 → 0.0.2

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 (137) hide show
  1. package/dist/main/AuthAdminApi.d.ts +4 -0
  2. package/dist/main/AuthAdminApi.d.ts.map +1 -0
  3. package/dist/main/AuthAdminApi.js +9 -0
  4. package/dist/main/AuthAdminApi.js.map +1 -0
  5. package/dist/main/AuthClient.d.ts +4 -0
  6. package/dist/main/AuthClient.d.ts.map +1 -0
  7. package/dist/main/AuthClient.js +9 -0
  8. package/dist/main/AuthClient.js.map +1 -0
  9. package/dist/main/GoTrueAdminApi.d.ts +99 -0
  10. package/dist/main/GoTrueAdminApi.d.ts.map +1 -0
  11. package/dist/main/GoTrueAdminApi.js +268 -0
  12. package/dist/main/GoTrueAdminApi.js.map +1 -0
  13. package/dist/main/GoTrueClient.d.ts +492 -0
  14. package/dist/main/GoTrueClient.d.ts.map +1 -0
  15. package/dist/main/GoTrueClient.js +2227 -0
  16. package/dist/main/GoTrueClient.js.map +1 -0
  17. package/dist/main/index.d.ts +9 -0
  18. package/dist/main/index.d.ts.map +1 -0
  19. package/dist/main/index.js +35 -0
  20. package/dist/main/index.js.map +1 -0
  21. package/dist/main/lib/version.d.ts +2 -0
  22. package/dist/main/lib/version.d.ts.map +1 -0
  23. package/dist/main/lib/version.js +6 -0
  24. package/dist/main/lib/version.js.map +1 -0
  25. package/dist/main/utils/base64url.d.ts +75 -0
  26. package/dist/main/utils/base64url.d.ts.map +1 -0
  27. package/dist/main/utils/base64url.js +270 -0
  28. package/dist/main/utils/base64url.js.map +1 -0
  29. package/dist/main/utils/constants.d.ts +26 -0
  30. package/dist/main/utils/constants.d.ts.map +1 -0
  31. package/dist/main/utils/constants.js +31 -0
  32. package/dist/main/utils/constants.js.map +1 -0
  33. package/dist/main/utils/error-codes.d.ts +7 -0
  34. package/dist/main/utils/error-codes.d.ts.map +1 -0
  35. package/dist/main/utils/error-codes.js +3 -0
  36. package/dist/main/utils/error-codes.js.map +1 -0
  37. package/dist/main/utils/errors.d.ts +100 -0
  38. package/dist/main/utils/errors.d.ts.map +1 -0
  39. package/dist/main/utils/errors.js +137 -0
  40. package/dist/main/utils/errors.js.map +1 -0
  41. package/dist/main/utils/fetch.d.ts +34 -0
  42. package/dist/main/utils/fetch.d.ts.map +1 -0
  43. package/dist/main/utils/fetch.js +195 -0
  44. package/dist/main/utils/fetch.js.map +1 -0
  45. package/dist/main/utils/helpers.d.ts +59 -0
  46. package/dist/main/utils/helpers.d.ts.map +1 -0
  47. package/dist/main/utils/helpers.js +334 -0
  48. package/dist/main/utils/helpers.js.map +1 -0
  49. package/dist/main/utils/local-storage.d.ts +13 -0
  50. package/dist/main/utils/local-storage.d.ts.map +1 -0
  51. package/dist/main/utils/local-storage.js +46 -0
  52. package/dist/main/utils/local-storage.js.map +1 -0
  53. package/dist/main/utils/locks.d.ts +64 -0
  54. package/dist/main/utils/locks.d.ts.map +1 -0
  55. package/dist/main/utils/locks.js +187 -0
  56. package/dist/main/utils/locks.js.map +1 -0
  57. package/dist/main/utils/polyfills.d.ts +5 -0
  58. package/dist/main/utils/polyfills.d.ts.map +1 -0
  59. package/dist/main/utils/polyfills.js +30 -0
  60. package/dist/main/utils/polyfills.js.map +1 -0
  61. package/dist/main/utils/types.d.ts +1074 -0
  62. package/dist/main/utils/types.d.ts.map +1 -0
  63. package/dist/main/utils/types.js +3 -0
  64. package/dist/main/utils/types.js.map +1 -0
  65. package/dist/main/utils/version.d.ts +2 -0
  66. package/dist/main/utils/version.d.ts.map +1 -0
  67. package/dist/main/utils/version.js +6 -0
  68. package/dist/main/utils/version.js.map +1 -0
  69. package/dist/module/AuthAdminApi.d.ts +4 -0
  70. package/dist/module/AuthAdminApi.d.ts.map +1 -0
  71. package/dist/module/AuthAdminApi.js +4 -0
  72. package/dist/module/AuthAdminApi.js.map +1 -0
  73. package/dist/module/AuthClient.d.ts +4 -0
  74. package/dist/module/AuthClient.d.ts.map +1 -0
  75. package/dist/module/AuthClient.js +4 -0
  76. package/dist/module/AuthClient.js.map +1 -0
  77. package/dist/module/GoTrueAdminApi.d.ts +99 -0
  78. package/dist/module/GoTrueAdminApi.d.ts.map +1 -0
  79. package/dist/module/GoTrueAdminApi.js +265 -0
  80. package/dist/module/GoTrueAdminApi.js.map +1 -0
  81. package/dist/module/GoTrueClient.d.ts +492 -0
  82. package/dist/module/GoTrueClient.d.ts.map +1 -0
  83. package/dist/module/GoTrueClient.js +2221 -0
  84. package/dist/module/GoTrueClient.js.map +1 -0
  85. package/dist/module/index.d.ts +9 -0
  86. package/dist/module/index.d.ts.map +1 -0
  87. package/dist/module/index.js +9 -0
  88. package/dist/module/index.js.map +1 -0
  89. package/dist/module/lib/version.d.ts +2 -0
  90. package/dist/module/lib/version.d.ts.map +1 -0
  91. package/dist/module/lib/version.js +3 -0
  92. package/dist/module/lib/version.js.map +1 -0
  93. package/dist/module/utils/base64url.d.ts +75 -0
  94. package/dist/module/utils/base64url.d.ts.map +1 -0
  95. package/dist/module/utils/base64url.js +257 -0
  96. package/dist/module/utils/base64url.js.map +1 -0
  97. package/dist/module/utils/constants.d.ts +26 -0
  98. package/dist/module/utils/constants.d.ts.map +1 -0
  99. package/dist/module/utils/constants.js +28 -0
  100. package/dist/module/utils/constants.js.map +1 -0
  101. package/dist/module/utils/error-codes.d.ts +7 -0
  102. package/dist/module/utils/error-codes.d.ts.map +1 -0
  103. package/dist/module/utils/error-codes.js +2 -0
  104. package/dist/module/utils/error-codes.js.map +1 -0
  105. package/dist/module/utils/errors.d.ts +100 -0
  106. package/dist/module/utils/errors.d.ts.map +1 -0
  107. package/dist/module/utils/errors.js +116 -0
  108. package/dist/module/utils/errors.js.map +1 -0
  109. package/dist/module/utils/fetch.d.ts +34 -0
  110. package/dist/module/utils/fetch.d.ts.map +1 -0
  111. package/dist/module/utils/fetch.js +184 -0
  112. package/dist/module/utils/fetch.js.map +1 -0
  113. package/dist/module/utils/helpers.d.ts +59 -0
  114. package/dist/module/utils/helpers.d.ts.map +1 -0
  115. package/dist/module/utils/helpers.js +288 -0
  116. package/dist/module/utils/helpers.js.map +1 -0
  117. package/dist/module/utils/local-storage.d.ts +13 -0
  118. package/dist/module/utils/local-storage.d.ts.map +1 -0
  119. package/dist/module/utils/local-storage.js +42 -0
  120. package/dist/module/utils/local-storage.js.map +1 -0
  121. package/dist/module/utils/locks.d.ts +64 -0
  122. package/dist/module/utils/locks.d.ts.map +1 -0
  123. package/dist/module/utils/locks.js +179 -0
  124. package/dist/module/utils/locks.js.map +1 -0
  125. package/dist/module/utils/polyfills.d.ts +5 -0
  126. package/dist/module/utils/polyfills.d.ts.map +1 -0
  127. package/dist/module/utils/polyfills.js +26 -0
  128. package/dist/module/utils/polyfills.js.map +1 -0
  129. package/dist/module/utils/types.d.ts +1074 -0
  130. package/dist/module/utils/types.d.ts.map +1 -0
  131. package/dist/module/utils/types.js +2 -0
  132. package/dist/module/utils/types.js.map +1 -0
  133. package/dist/module/utils/version.d.ts +2 -0
  134. package/dist/module/utils/version.d.ts.map +1 -0
  135. package/dist/module/utils/version.js +3 -0
  136. package/dist/module/utils/version.js.map +1 -0
  137. package/package.json +2 -2
@@ -0,0 +1,2221 @@
1
+ import GoTrueAdminApi from './GoTrueAdminApi';
2
+ import { DEFAULT_HEADERS, EXPIRY_MARGIN_MS, AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, GOTRUE_URL, STORAGE_KEY, JWKS_TTL, } from './utils/constants';
3
+ import { AuthImplicitGrantRedirectError, AuthPKCEGrantCodeExchangeError, AuthInvalidCredentialsError, AuthSessionMissingError, AuthInvalidTokenResponseError, AuthUnknownError, isAuthApiError, isAuthError, isAuthRetryableFetchError, isAuthSessionMissingError, isAuthImplicitGrantRedirectError, AuthInvalidJwtError, } from './utils/errors';
4
+ import { _request, _sessionResponse, _sessionResponsePassword, _userResponse, _ssoResponse, } from './utils/fetch';
5
+ import { Deferred, getItemAsync, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, supportsLocalStorage, parseParametersFromURL, getCodeChallengeAndMethod, getAlgorithm, validateExp, decodeJWT, } from './utils/helpers';
6
+ import { localStorageAdapter, memoryLocalStorageAdapter } from './utils/local-storage';
7
+ import { polyfillGlobalThis } from './utils/polyfills';
8
+ import { version } from './utils/version';
9
+ import { LockAcquireTimeoutError, navigatorLock } from './utils/locks';
10
+ import { stringToUint8Array, bytesToBase64URL } from './utils/base64url';
11
+ polyfillGlobalThis(); // Make "globalThis" available
12
+ const DEFAULT_OPTIONS = {
13
+ url: GOTRUE_URL,
14
+ storageKey: STORAGE_KEY,
15
+ autoRefreshToken: true,
16
+ persistSession: true,
17
+ detectSessionInUrl: true,
18
+ headers: DEFAULT_HEADERS,
19
+ flowType: 'implicit',
20
+ debug: false,
21
+ hasCustomAuthorizationHeader: false,
22
+ };
23
+ async function lockNoOp(name, acquireTimeout, fn) {
24
+ return await fn();
25
+ }
26
+ export default class GoTrueClient {
27
+ /**
28
+ * Create a new client for use in the browser.
29
+ */
30
+ constructor(options) {
31
+ var _a, _b;
32
+ this.memoryStorage = null;
33
+ this.stateChangeEmitters = new Map();
34
+ this.autoRefreshTicker = null;
35
+ this.visibilityChangedCallback = null;
36
+ this.refreshingDeferred = null;
37
+ /**
38
+ * Keeps track of the async client initialization.
39
+ * When null or not yet resolved the auth state is `unknown`
40
+ * Once resolved the the auth state is known and it's save to call any further client methods.
41
+ * Keep extra care to never reject or throw uncaught errors
42
+ */
43
+ this.initializePromise = null;
44
+ this.detectSessionInUrl = true;
45
+ this.hasCustomAuthorizationHeader = false;
46
+ this.suppressGetSessionWarning = false;
47
+ this.lockAcquired = false;
48
+ this.pendingInLock = [];
49
+ /**
50
+ * Used to broadcast state change events to other tabs listening.
51
+ */
52
+ this.broadcastChannel = null;
53
+ this.logger = console.log;
54
+ this.instanceID = GoTrueClient.nextInstanceID;
55
+ GoTrueClient.nextInstanceID += 1;
56
+ if (this.instanceID > 0 && isBrowser()) {
57
+ console.warn('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.');
58
+ }
59
+ const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
60
+ this.logDebugMessages = !!settings.debug;
61
+ if (typeof settings.debug === 'function') {
62
+ this.logger = settings.debug;
63
+ }
64
+ this.persistSession = settings.persistSession;
65
+ this.storageKey = settings.storageKey;
66
+ this.autoRefreshToken = settings.autoRefreshToken;
67
+ this.admin = new GoTrueAdminApi({
68
+ url: settings.url,
69
+ headers: settings.headers,
70
+ fetch: settings.fetch,
71
+ });
72
+ this.url = settings.url;
73
+ this.headers = settings.headers;
74
+ this.fetch = resolveFetch(settings.fetch);
75
+ this.lock = settings.lock || lockNoOp;
76
+ this.detectSessionInUrl = settings.detectSessionInUrl;
77
+ this.flowType = settings.flowType;
78
+ this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader;
79
+ if (settings.lock) {
80
+ this.lock = settings.lock;
81
+ }
82
+ else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) {
83
+ this.lock = navigatorLock;
84
+ }
85
+ else {
86
+ this.lock = lockNoOp;
87
+ }
88
+ this.jwks = { keys: [] };
89
+ this.jwks_cached_at = Number.MIN_SAFE_INTEGER;
90
+ this.mfa = {
91
+ verify: this._verify.bind(this),
92
+ enroll: this._enroll.bind(this),
93
+ unenroll: this._unenroll.bind(this),
94
+ challenge: this._challenge.bind(this),
95
+ listFactors: this._listFactors.bind(this),
96
+ challengeAndVerify: this._challengeAndVerify.bind(this),
97
+ getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
98
+ };
99
+ if (this.persistSession) {
100
+ if (settings.storage) {
101
+ this.storage = settings.storage;
102
+ }
103
+ else {
104
+ if (supportsLocalStorage()) {
105
+ this.storage = localStorageAdapter;
106
+ }
107
+ else {
108
+ this.memoryStorage = {};
109
+ this.storage = memoryLocalStorageAdapter(this.memoryStorage);
110
+ }
111
+ }
112
+ }
113
+ else {
114
+ this.memoryStorage = {};
115
+ this.storage = memoryLocalStorageAdapter(this.memoryStorage);
116
+ }
117
+ if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
118
+ try {
119
+ this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
120
+ }
121
+ catch (e) {
122
+ console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e);
123
+ }
124
+ (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => {
125
+ this._debug('received broadcast notification from other tab or client', event);
126
+ await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages
127
+ });
128
+ }
129
+ this.initialize();
130
+ }
131
+ _debug(...args) {
132
+ if (this.logDebugMessages) {
133
+ this.logger(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args);
134
+ }
135
+ return this;
136
+ }
137
+ /**
138
+ * Initializes the client session either from the url or from storage.
139
+ * This method is automatically called when instantiating the client, but should also be called
140
+ * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
141
+ */
142
+ async initialize() {
143
+ if (this.initializePromise) {
144
+ return await this.initializePromise;
145
+ }
146
+ this.initializePromise = (async () => {
147
+ return await this._acquireLock(-1, async () => {
148
+ return await this._initialize();
149
+ });
150
+ })();
151
+ return await this.initializePromise;
152
+ }
153
+ /**
154
+ * IMPORTANT:
155
+ * 1. Never throw in this method, as it is called from the constructor
156
+ * 2. Never return a session from this method as it would be cached over
157
+ * the whole lifetime of the client
158
+ */
159
+ async _initialize() {
160
+ var _a;
161
+ try {
162
+ const params = parseParametersFromURL(window.location.href);
163
+ let callbackUrlType = 'none';
164
+ if (this._isImplicitGrantCallback(params)) {
165
+ callbackUrlType = 'implicit';
166
+ }
167
+ else if (await this._isPKCECallback(params)) {
168
+ callbackUrlType = 'pkce';
169
+ }
170
+ /**
171
+ * Attempt to get the session from the URL only if these conditions are fulfilled
172
+ *
173
+ * Note: If the URL isn't one of the callback url types (implicit or pkce),
174
+ * then there could be an existing session so we don't want to prematurely remove it
175
+ */
176
+ if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {
177
+ const { data, error } = await this._getSessionFromURL(params, callbackUrlType);
178
+ if (error) {
179
+ this._debug('#_initialize()', 'error detecting session from URL', error);
180
+ if (isAuthImplicitGrantRedirectError(error)) {
181
+ const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code;
182
+ if (errorCode === 'identity_already_exists' ||
183
+ errorCode === 'identity_not_found' ||
184
+ errorCode === 'single_identity_not_deletable') {
185
+ return { error };
186
+ }
187
+ }
188
+ // failed login attempt via url,
189
+ // remove old session as in verifyOtp, signUp and signInWith*
190
+ await this._removeSession();
191
+ return { error };
192
+ }
193
+ const { session, redirectType } = data;
194
+ this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType);
195
+ await this._saveSession(session);
196
+ setTimeout(async () => {
197
+ if (redirectType === 'recovery') {
198
+ await this._notifyAllSubscribers('PASSWORD_RECOVERY', session);
199
+ }
200
+ else {
201
+ await this._notifyAllSubscribers('SIGNED_IN', session);
202
+ }
203
+ }, 0);
204
+ return { error: null };
205
+ }
206
+ // no login attempt via callback url try to recover session from storage
207
+ await this._recoverAndRefresh();
208
+ return { error: null };
209
+ }
210
+ catch (error) {
211
+ if (isAuthError(error)) {
212
+ return { error };
213
+ }
214
+ return {
215
+ error: new AuthUnknownError('Unexpected error during initialization', error),
216
+ };
217
+ }
218
+ finally {
219
+ await this._handleVisibilityChange();
220
+ this._debug('#_initialize()', 'end');
221
+ }
222
+ }
223
+ /**
224
+ * Creates a new anonymous user.
225
+ *
226
+ * @returns A session where the is_anonymous claim in the access token JWT set to true
227
+ */
228
+ async signInAnonymously(credentials) {
229
+ var _a, _b, _c;
230
+ try {
231
+ const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
232
+ headers: this.headers,
233
+ body: {
234
+ 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 : {},
235
+ gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken },
236
+ },
237
+ xform: _sessionResponse,
238
+ });
239
+ const { data, error } = res;
240
+ if (error || !data) {
241
+ return { data: { user: null, session: null }, error: error };
242
+ }
243
+ const session = data.session;
244
+ const user = data.user;
245
+ if (data.session) {
246
+ await this._saveSession(data.session);
247
+ await this._notifyAllSubscribers('SIGNED_IN', session);
248
+ }
249
+ return { data: { user, session }, error: null };
250
+ }
251
+ catch (error) {
252
+ if (isAuthError(error)) {
253
+ return { data: { user: null, session: null }, error };
254
+ }
255
+ throw error;
256
+ }
257
+ }
258
+ /**
259
+ * Creates a new user.
260
+ *
261
+ * Be aware that if a user account exists in the system you may get back an
262
+ * error message that attempts to hide this information from the user.
263
+ * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
264
+ *
265
+ * @returns A logged-in session if the server has "autoconfirm" ON
266
+ * @returns A user if the server has "autoconfirm" OFF
267
+ */
268
+ async signUp(credentials) {
269
+ var _a, _b, _c;
270
+ try {
271
+ let res;
272
+ if ('email' in credentials) {
273
+ const { email, password, options } = credentials;
274
+ let codeChallenge = null;
275
+ let codeChallengeMethod = null;
276
+ if (this.flowType === 'pkce') {
277
+ ;
278
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
279
+ }
280
+ res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
281
+ headers: this.headers,
282
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
283
+ body: {
284
+ email,
285
+ password,
286
+ data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
287
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
288
+ code_challenge: codeChallenge,
289
+ code_challenge_method: codeChallengeMethod,
290
+ },
291
+ xform: _sessionResponse,
292
+ });
293
+ }
294
+ else if ('phone' in credentials) {
295
+ const { phone, password, options } = credentials;
296
+ res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
297
+ headers: this.headers,
298
+ body: {
299
+ phone,
300
+ password,
301
+ data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},
302
+ channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms',
303
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
304
+ },
305
+ xform: _sessionResponse,
306
+ });
307
+ }
308
+ else {
309
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
310
+ }
311
+ const { data, error } = res;
312
+ if (error || !data) {
313
+ return { data: { user: null, session: null }, error: error };
314
+ }
315
+ const session = data.session;
316
+ const user = data.user;
317
+ if (data.session) {
318
+ await this._saveSession(data.session);
319
+ await this._notifyAllSubscribers('SIGNED_IN', session);
320
+ }
321
+ return { data: { user, session }, error: null };
322
+ }
323
+ catch (error) {
324
+ if (isAuthError(error)) {
325
+ return { data: { user: null, session: null }, error };
326
+ }
327
+ throw error;
328
+ }
329
+ }
330
+ /**
331
+ * Log in an existing user with an email and password or phone and password.
332
+ *
333
+ * Be aware that you may get back an error message that will not distinguish
334
+ * between the cases where the account does not exist or that the
335
+ * email/phone and password combination is wrong or that the account can only
336
+ * be accessed via social login.
337
+ */
338
+ async signInWithPassword(credentials) {
339
+ try {
340
+ let res;
341
+ if ('email' in credentials) {
342
+ const { email, password, options } = credentials;
343
+ res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
344
+ headers: this.headers,
345
+ body: {
346
+ email,
347
+ password,
348
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
349
+ },
350
+ xform: _sessionResponsePassword,
351
+ });
352
+ }
353
+ else if ('phone' in credentials) {
354
+ const { phone, password, options } = credentials;
355
+ res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
356
+ headers: this.headers,
357
+ body: {
358
+ phone,
359
+ password,
360
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
361
+ },
362
+ xform: _sessionResponsePassword,
363
+ });
364
+ }
365
+ else {
366
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
367
+ }
368
+ const { data, error } = res;
369
+ if (error) {
370
+ return { data: { user: null, session: null }, error };
371
+ }
372
+ else if (!data || !data.session || !data.user) {
373
+ return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() };
374
+ }
375
+ if (data.session) {
376
+ await this._saveSession(data.session);
377
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
378
+ }
379
+ return {
380
+ data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)),
381
+ error,
382
+ };
383
+ }
384
+ catch (error) {
385
+ if (isAuthError(error)) {
386
+ return { data: { user: null, session: null }, error };
387
+ }
388
+ throw error;
389
+ }
390
+ }
391
+ /**
392
+ * Log in an existing user via a third-party provider.
393
+ * This method supports the PKCE flow.
394
+ */
395
+ async signInWithOAuth(credentials) {
396
+ var _a, _b, _c, _d;
397
+ return await this._handleProviderSignIn(credentials.provider, {
398
+ redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
399
+ scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
400
+ queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
401
+ skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect,
402
+ });
403
+ }
404
+ /**
405
+ * Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
406
+ */
407
+ async exchangeCodeForSession(authCode) {
408
+ await this.initializePromise;
409
+ return this._acquireLock(-1, async () => {
410
+ return this._exchangeCodeForSession(authCode);
411
+ });
412
+ }
413
+ /**
414
+ * Signs in a user by verifying a message signed by the user's private key.
415
+ * Only Solana supported at this time, using the Sign in with Solana standard.
416
+ */
417
+ async signInWithWeb3(credentials) {
418
+ const { chain } = credentials;
419
+ if (chain === 'solana') {
420
+ return await this.signInWithSolana(credentials);
421
+ }
422
+ throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`);
423
+ }
424
+ async signInWithSolana(credentials) {
425
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
426
+ let message;
427
+ let signature;
428
+ if ('message' in credentials) {
429
+ message = credentials.message;
430
+ signature = credentials.signature;
431
+ }
432
+ else {
433
+ const { chain, wallet, statement, options } = credentials;
434
+ let resolvedWallet;
435
+ if (!isBrowser()) {
436
+ if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) {
437
+ throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.');
438
+ }
439
+ resolvedWallet = wallet;
440
+ }
441
+ else if (typeof wallet === 'object') {
442
+ resolvedWallet = wallet;
443
+ }
444
+ else {
445
+ const windowAny = window;
446
+ if ('solana' in windowAny &&
447
+ typeof windowAny.solana === 'object' &&
448
+ (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') ||
449
+ ('signMessage' in windowAny.solana &&
450
+ typeof windowAny.solana.signMessage === 'function'))) {
451
+ resolvedWallet = windowAny.solana;
452
+ }
453
+ else {
454
+ 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.`);
455
+ }
456
+ }
457
+ const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href);
458
+ if ('signIn' in resolvedWallet && resolvedWallet.signIn) {
459
+ const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), {
460
+ // non-overridable properties
461
+ version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null)));
462
+ let outputToProcess;
463
+ if (Array.isArray(output) && output[0] && typeof output[0] === 'object') {
464
+ outputToProcess = output[0];
465
+ }
466
+ else if (output &&
467
+ typeof output === 'object' &&
468
+ 'signedMessage' in output &&
469
+ 'signature' in output) {
470
+ outputToProcess = output;
471
+ }
472
+ else {
473
+ throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value');
474
+ }
475
+ if ('signedMessage' in outputToProcess &&
476
+ 'signature' in outputToProcess &&
477
+ (typeof outputToProcess.signedMessage === 'string' ||
478
+ outputToProcess.signedMessage instanceof Uint8Array) &&
479
+ outputToProcess.signature instanceof Uint8Array) {
480
+ message =
481
+ typeof outputToProcess.signedMessage === 'string'
482
+ ? outputToProcess.signedMessage
483
+ : new TextDecoder().decode(outputToProcess.signedMessage);
484
+ signature = outputToProcess.signature;
485
+ }
486
+ else {
487
+ throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields');
488
+ }
489
+ }
490
+ else {
491
+ if (!('signMessage' in resolvedWallet) ||
492
+ typeof resolvedWallet.signMessage !== 'function' ||
493
+ !('publicKey' in resolvedWallet) ||
494
+ typeof resolvedWallet !== 'object' ||
495
+ !resolvedWallet.publicKey ||
496
+ !('toBase58' in resolvedWallet.publicKey) ||
497
+ typeof resolvedWallet.publicKey.toBase58 !== 'function') {
498
+ throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API');
499
+ }
500
+ message = [
501
+ `${url.host} wants you to sign in with your Solana account:`,
502
+ resolvedWallet.publicKey.toBase58(),
503
+ ...(statement ? ['', statement, ''] : ['']),
504
+ 'Version: 1',
505
+ `URI: ${url.href}`,
506
+ `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()}`,
507
+ ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore)
508
+ ? [`Not Before: ${options.signInWithSolana.notBefore}`]
509
+ : []),
510
+ ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime)
511
+ ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`]
512
+ : []),
513
+ ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId)
514
+ ? [`Chain ID: ${options.signInWithSolana.chainId}`]
515
+ : []),
516
+ ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []),
517
+ ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId)
518
+ ? [`Request ID: ${options.signInWithSolana.requestId}`]
519
+ : []),
520
+ ...(((_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)
521
+ ? [
522
+ 'Resources',
523
+ ...options.signInWithSolana.resources.map((resource) => `- ${resource}`),
524
+ ]
525
+ : []),
526
+ ].join('\n');
527
+ const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8');
528
+ if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) {
529
+ throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value');
530
+ }
531
+ signature = maybeSignature;
532
+ }
533
+ }
534
+ try {
535
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, {
536
+ headers: this.headers,
537
+ body: Object.assign({ chain: 'solana', message, signature: bytesToBase64URL(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken)
538
+ ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } }
539
+ : null)),
540
+ xform: _sessionResponse,
541
+ });
542
+ if (error) {
543
+ throw error;
544
+ }
545
+ if (!data || !data.session || !data.user) {
546
+ return {
547
+ data: { user: null, session: null },
548
+ error: new AuthInvalidTokenResponseError(),
549
+ };
550
+ }
551
+ if (data.session) {
552
+ await this._saveSession(data.session);
553
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
554
+ }
555
+ return { data: Object.assign({}, data), error };
556
+ }
557
+ catch (error) {
558
+ if (isAuthError(error)) {
559
+ return { data: { user: null, session: null }, error };
560
+ }
561
+ throw error;
562
+ }
563
+ }
564
+ async _exchangeCodeForSession(authCode) {
565
+ const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
566
+ const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/');
567
+ try {
568
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, {
569
+ headers: this.headers,
570
+ body: {
571
+ auth_code: authCode,
572
+ code_verifier: codeVerifier,
573
+ },
574
+ xform: _sessionResponse,
575
+ });
576
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
577
+ if (error) {
578
+ throw error;
579
+ }
580
+ if (!data || !data.session || !data.user) {
581
+ return {
582
+ data: { user: null, session: null, redirectType: null },
583
+ error: new AuthInvalidTokenResponseError(),
584
+ };
585
+ }
586
+ if (data.session) {
587
+ await this._saveSession(data.session);
588
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
589
+ }
590
+ return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error };
591
+ }
592
+ catch (error) {
593
+ if (isAuthError(error)) {
594
+ return { data: { user: null, session: null, redirectType: null }, error };
595
+ }
596
+ throw error;
597
+ }
598
+ }
599
+ /**
600
+ * Allows signing in with an OIDC ID token. The authentication provider used
601
+ * should be enabled and configured.
602
+ */
603
+ async signInWithIdToken(credentials) {
604
+ try {
605
+ const { options, provider, token, access_token, nonce } = credentials;
606
+ const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {
607
+ headers: this.headers,
608
+ body: {
609
+ provider,
610
+ id_token: token,
611
+ access_token,
612
+ nonce,
613
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
614
+ },
615
+ xform: _sessionResponse,
616
+ });
617
+ const { data, error } = res;
618
+ if (error) {
619
+ return { data: { user: null, session: null }, error };
620
+ }
621
+ else if (!data || !data.session || !data.user) {
622
+ return {
623
+ data: { user: null, session: null },
624
+ error: new AuthInvalidTokenResponseError(),
625
+ };
626
+ }
627
+ if (data.session) {
628
+ await this._saveSession(data.session);
629
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
630
+ }
631
+ return { data, error };
632
+ }
633
+ catch (error) {
634
+ if (isAuthError(error)) {
635
+ return { data: { user: null, session: null }, error };
636
+ }
637
+ throw error;
638
+ }
639
+ }
640
+ /**
641
+ * Log in a user using magiclink or a one-time password (OTP).
642
+ *
643
+ * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
644
+ * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
645
+ * 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.
646
+ *
647
+ * Be aware that you may get back an error message that will not distinguish
648
+ * between the cases where the account does not exist or, that the account
649
+ * can only be accessed via social login.
650
+ *
651
+ * Do note that you will need to configure a Whatsapp sender on Twilio
652
+ * if you are using phone sign in with the 'whatsapp' channel. The whatsapp
653
+ * channel is not supported on other providers
654
+ * at this time.
655
+ * This method supports PKCE when an email is passed.
656
+ */
657
+ async signInWithOtp(credentials) {
658
+ var _a, _b, _c, _d, _e;
659
+ try {
660
+ if ('email' in credentials) {
661
+ const { email, options } = credentials;
662
+ let codeChallenge = null;
663
+ let codeChallengeMethod = null;
664
+ if (this.flowType === 'pkce') {
665
+ ;
666
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
667
+ }
668
+ const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
669
+ headers: this.headers,
670
+ body: {
671
+ email,
672
+ data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
673
+ create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true,
674
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
675
+ code_challenge: codeChallenge,
676
+ code_challenge_method: codeChallengeMethod,
677
+ },
678
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
679
+ });
680
+ return { data: { user: null, session: null }, error };
681
+ }
682
+ if ('phone' in credentials) {
683
+ const { phone, options } = credentials;
684
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
685
+ headers: this.headers,
686
+ body: {
687
+ phone,
688
+ data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {},
689
+ create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true,
690
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
691
+ channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms',
692
+ },
693
+ });
694
+ return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error };
695
+ }
696
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number.');
697
+ }
698
+ catch (error) {
699
+ if (isAuthError(error)) {
700
+ return { data: { user: null, session: null }, error };
701
+ }
702
+ throw error;
703
+ }
704
+ }
705
+ /**
706
+ * Log in a user given a User supplied OTP or TokenHash received through mobile or email.
707
+ */
708
+ async verifyOtp(params) {
709
+ var _a, _b;
710
+ try {
711
+ let redirectTo = undefined;
712
+ let captchaToken = undefined;
713
+ if ('options' in params) {
714
+ redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo;
715
+ captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken;
716
+ }
717
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {
718
+ headers: this.headers,
719
+ body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }),
720
+ redirectTo,
721
+ xform: _sessionResponse,
722
+ });
723
+ if (error) {
724
+ throw error;
725
+ }
726
+ if (!data) {
727
+ throw new Error('An error occurred on token verification.');
728
+ }
729
+ const session = data.session;
730
+ const user = data.user;
731
+ if (session === null || session === void 0 ? void 0 : session.access_token) {
732
+ await this._saveSession(session);
733
+ await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session);
734
+ }
735
+ return { data: { user, session }, error: null };
736
+ }
737
+ catch (error) {
738
+ if (isAuthError(error)) {
739
+ return { data: { user: null, session: null }, error };
740
+ }
741
+ throw error;
742
+ }
743
+ }
744
+ /**
745
+ * Attempts a single-sign on using an enterprise Identity Provider. A
746
+ * successful SSO attempt will redirect the current page to the identity
747
+ * provider authorization page. The redirect URL is implementation and SSO
748
+ * protocol specific.
749
+ *
750
+ * You can use it by providing a SSO domain. Typically you can extract this
751
+ * domain by asking users for their email address. If this domain is
752
+ * registered on the Auth instance the redirect will use that organization's
753
+ * currently active SSO Identity Provider for the login.
754
+ *
755
+ * If you have built an organization-specific login page, you can use the
756
+ * organization's SSO Identity Provider UUID directly instead.
757
+ */
758
+ async signInWithSSO(params) {
759
+ var _a, _b, _c;
760
+ try {
761
+ let codeChallenge = null;
762
+ let codeChallengeMethod = null;
763
+ if (this.flowType === 'pkce') {
764
+ ;
765
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
766
+ }
767
+ return await _request(this.fetch, 'POST', `${this.url}/sso`, {
768
+ 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)
769
+ ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }
770
+ : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
771
+ headers: this.headers,
772
+ xform: _ssoResponse,
773
+ });
774
+ }
775
+ catch (error) {
776
+ if (isAuthError(error)) {
777
+ return { data: null, error };
778
+ }
779
+ throw error;
780
+ }
781
+ }
782
+ /**
783
+ * Sends a reauthentication OTP to the user's email or phone number.
784
+ * Requires the user to be signed-in.
785
+ */
786
+ async reauthenticate() {
787
+ await this.initializePromise;
788
+ return await this._acquireLock(-1, async () => {
789
+ return await this._reauthenticate();
790
+ });
791
+ }
792
+ async _reauthenticate() {
793
+ try {
794
+ return await this._useSession(async (result) => {
795
+ const { data: { session }, error: sessionError, } = result;
796
+ if (sessionError)
797
+ throw sessionError;
798
+ if (!session)
799
+ throw new AuthSessionMissingError();
800
+ const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {
801
+ headers: this.headers,
802
+ jwt: session.access_token,
803
+ });
804
+ return { data: { user: null, session: null }, error };
805
+ });
806
+ }
807
+ catch (error) {
808
+ if (isAuthError(error)) {
809
+ return { data: { user: null, session: null }, error };
810
+ }
811
+ throw error;
812
+ }
813
+ }
814
+ /**
815
+ * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
816
+ */
817
+ async resend(credentials) {
818
+ try {
819
+ const endpoint = `${this.url}/resend`;
820
+ if ('email' in credentials) {
821
+ const { email, type, options } = credentials;
822
+ const { error } = await _request(this.fetch, 'POST', endpoint, {
823
+ headers: this.headers,
824
+ body: {
825
+ email,
826
+ type,
827
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
828
+ },
829
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
830
+ });
831
+ return { data: { user: null, session: null }, error };
832
+ }
833
+ else if ('phone' in credentials) {
834
+ const { phone, type, options } = credentials;
835
+ const { data, error } = await _request(this.fetch, 'POST', endpoint, {
836
+ headers: this.headers,
837
+ body: {
838
+ phone,
839
+ type,
840
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
841
+ },
842
+ });
843
+ return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error };
844
+ }
845
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type');
846
+ }
847
+ catch (error) {
848
+ if (isAuthError(error)) {
849
+ return { data: { user: null, session: null }, error };
850
+ }
851
+ throw error;
852
+ }
853
+ }
854
+ /**
855
+ * Returns the session, refreshing it if necessary.
856
+ *
857
+ * 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.
858
+ *
859
+ * **IMPORTANT:** This method loads values directly from the storage attached
860
+ * to the client. If that storage is based on request cookies for example,
861
+ * the values in it may not be authentic and therefore it's strongly advised
862
+ * against using this method and its results in such circumstances. A warning
863
+ * will be emitted if this is detected. Use {@link #getUser()} instead.
864
+ */
865
+ async getSession() {
866
+ await this.initializePromise;
867
+ const result = await this._acquireLock(-1, async () => {
868
+ return this._useSession(async (result) => {
869
+ return result;
870
+ });
871
+ });
872
+ return result;
873
+ }
874
+ /**
875
+ * Acquires a global lock based on the storage key.
876
+ */
877
+ async _acquireLock(acquireTimeout, fn) {
878
+ this._debug('#_acquireLock', 'begin', acquireTimeout);
879
+ try {
880
+ if (this.lockAcquired) {
881
+ const last = this.pendingInLock.length
882
+ ? this.pendingInLock[this.pendingInLock.length - 1]
883
+ : Promise.resolve();
884
+ const result = (async () => {
885
+ await last;
886
+ return await fn();
887
+ })();
888
+ this.pendingInLock.push((async () => {
889
+ try {
890
+ await result;
891
+ }
892
+ catch (e) {
893
+ // we just care if it finished
894
+ }
895
+ })());
896
+ return result;
897
+ }
898
+ return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {
899
+ this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey);
900
+ try {
901
+ this.lockAcquired = true;
902
+ const result = fn();
903
+ this.pendingInLock.push((async () => {
904
+ try {
905
+ await result;
906
+ }
907
+ catch (e) {
908
+ // we just care if it finished
909
+ }
910
+ })());
911
+ await result;
912
+ // keep draining the queue until there's nothing to wait on
913
+ while (this.pendingInLock.length) {
914
+ const waitOn = [...this.pendingInLock];
915
+ await Promise.all(waitOn);
916
+ this.pendingInLock.splice(0, waitOn.length);
917
+ }
918
+ return await result;
919
+ }
920
+ finally {
921
+ this._debug('#_acquireLock', 'lock released for storage key', this.storageKey);
922
+ this.lockAcquired = false;
923
+ }
924
+ });
925
+ }
926
+ finally {
927
+ this._debug('#_acquireLock', 'end');
928
+ }
929
+ }
930
+ /**
931
+ * Use instead of {@link #getSession} inside the library. It is
932
+ * semantically usually what you want, as getting a session involves some
933
+ * processing afterwards that requires only one client operating on the
934
+ * session at once across multiple tabs or processes.
935
+ */
936
+ async _useSession(fn) {
937
+ this._debug('#_useSession', 'begin');
938
+ try {
939
+ // the use of __loadSession here is the only correct use of the function!
940
+ const result = await this.__loadSession();
941
+ return await fn(result);
942
+ }
943
+ finally {
944
+ this._debug('#_useSession', 'end');
945
+ }
946
+ }
947
+ /**
948
+ * NEVER USE DIRECTLY!
949
+ *
950
+ * Always use {@link #_useSession}.
951
+ */
952
+ async __loadSession() {
953
+ this._debug('#__loadSession()', 'begin');
954
+ if (!this.lockAcquired) {
955
+ this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack);
956
+ }
957
+ try {
958
+ let currentSession = null;
959
+ const maybeSession = await getItemAsync(this.storage, this.storageKey);
960
+ this._debug('#getSession()', 'session from storage', maybeSession);
961
+ if (maybeSession !== null) {
962
+ if (this._isValidSession(maybeSession)) {
963
+ currentSession = maybeSession;
964
+ }
965
+ else {
966
+ this._debug('#getSession()', 'session from storage is not valid');
967
+ await this._removeSession();
968
+ }
969
+ }
970
+ if (!currentSession) {
971
+ return { data: { session: null }, error: null };
972
+ }
973
+ // A session is considered expired before the access token _actually_
974
+ // expires. When the autoRefreshToken option is off (or when the tab is
975
+ // in the background), very eager users of getSession() -- like
976
+ // realtime-js -- might send a valid JWT which will expire by the time it
977
+ // reaches the server.
978
+ const hasExpired = currentSession.expires_at
979
+ ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS
980
+ : false;
981
+ this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at);
982
+ if (!hasExpired) {
983
+ if (this.storage.isServer) {
984
+ let suppressWarning = this.suppressGetSessionWarning;
985
+ const proxySession = new Proxy(currentSession, {
986
+ get: (target, prop, receiver) => {
987
+ if (!suppressWarning && prop === 'user') {
988
+ // only show warning when the user object is being accessed from the server
989
+ console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.');
990
+ suppressWarning = true; // keeps this proxy instance from logging additional warnings
991
+ this.suppressGetSessionWarning = true; // keeps this client's future proxy instances from warning
992
+ }
993
+ return Reflect.get(target, prop, receiver);
994
+ },
995
+ });
996
+ currentSession = proxySession;
997
+ }
998
+ return { data: { session: currentSession }, error: null };
999
+ }
1000
+ const { session, error } = await this._callRefreshToken(currentSession.refresh_token);
1001
+ if (error) {
1002
+ return { data: { session: null }, error };
1003
+ }
1004
+ return { data: { session }, error: null };
1005
+ }
1006
+ finally {
1007
+ this._debug('#__loadSession()', 'end');
1008
+ }
1009
+ }
1010
+ /**
1011
+ * Gets the current user details if there is an existing session. This method
1012
+ * performs a network request to the Supabase Auth server, so the returned
1013
+ * value is authentic and can be used to base authorization rules on.
1014
+ *
1015
+ * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
1016
+ */
1017
+ async getUser(jwt) {
1018
+ if (jwt) {
1019
+ return await this._getUser(jwt);
1020
+ }
1021
+ await this.initializePromise;
1022
+ const result = await this._acquireLock(-1, async () => {
1023
+ return await this._getUser();
1024
+ });
1025
+ return result;
1026
+ }
1027
+ async _getUser(jwt) {
1028
+ try {
1029
+ if (jwt) {
1030
+ return await _request(this.fetch, 'GET', `${this.url}/user`, {
1031
+ headers: this.headers,
1032
+ jwt: jwt,
1033
+ xform: _userResponse,
1034
+ });
1035
+ }
1036
+ return await this._useSession(async (result) => {
1037
+ var _a, _b, _c;
1038
+ const { data, error } = result;
1039
+ if (error) {
1040
+ throw error;
1041
+ }
1042
+ // returns an error if there is no access_token or custom authorization header
1043
+ if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) {
1044
+ return { data: { user: null }, error: new AuthSessionMissingError() };
1045
+ }
1046
+ return await _request(this.fetch, 'GET', `${this.url}/user`, {
1047
+ headers: this.headers,
1048
+ jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined,
1049
+ xform: _userResponse,
1050
+ });
1051
+ });
1052
+ }
1053
+ catch (error) {
1054
+ if (isAuthError(error)) {
1055
+ if (isAuthSessionMissingError(error)) {
1056
+ // JWT contains a `session_id` which does not correspond to an active
1057
+ // session in the database, indicating the user is signed out.
1058
+ await this._removeSession();
1059
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1060
+ }
1061
+ return { data: { user: null }, error };
1062
+ }
1063
+ throw error;
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Updates user data for a logged in user.
1068
+ */
1069
+ async updateUser(attributes, options = {}) {
1070
+ await this.initializePromise;
1071
+ return await this._acquireLock(-1, async () => {
1072
+ return await this._updateUser(attributes, options);
1073
+ });
1074
+ }
1075
+ async _updateUser(attributes, options = {}) {
1076
+ try {
1077
+ return await this._useSession(async (result) => {
1078
+ const { data: sessionData, error: sessionError } = result;
1079
+ if (sessionError) {
1080
+ throw sessionError;
1081
+ }
1082
+ if (!sessionData.session) {
1083
+ throw new AuthSessionMissingError();
1084
+ }
1085
+ const session = sessionData.session;
1086
+ let codeChallenge = null;
1087
+ let codeChallengeMethod = null;
1088
+ if (this.flowType === 'pkce' && attributes.email != null) {
1089
+ ;
1090
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
1091
+ }
1092
+ const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {
1093
+ headers: this.headers,
1094
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
1095
+ body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
1096
+ jwt: session.access_token,
1097
+ xform: _userResponse,
1098
+ });
1099
+ if (userError)
1100
+ throw userError;
1101
+ session.user = data.user;
1102
+ await this._saveSession(session);
1103
+ await this._notifyAllSubscribers('USER_UPDATED', session);
1104
+ return { data: { user: session.user }, error: null };
1105
+ });
1106
+ }
1107
+ catch (error) {
1108
+ if (isAuthError(error)) {
1109
+ return { data: { user: null }, error };
1110
+ }
1111
+ throw error;
1112
+ }
1113
+ }
1114
+ /**
1115
+ * 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.
1116
+ * If the refresh token or access token in the current session is invalid, an error will be thrown.
1117
+ * @param currentSession The current session that minimally contains an access token and refresh token.
1118
+ */
1119
+ async setSession(currentSession) {
1120
+ await this.initializePromise;
1121
+ return await this._acquireLock(-1, async () => {
1122
+ return await this._setSession(currentSession);
1123
+ });
1124
+ }
1125
+ async _setSession(currentSession) {
1126
+ try {
1127
+ if (!currentSession.access_token || !currentSession.refresh_token) {
1128
+ throw new AuthSessionMissingError();
1129
+ }
1130
+ const timeNow = Date.now() / 1000;
1131
+ let expiresAt = timeNow;
1132
+ let hasExpired = true;
1133
+ let session = null;
1134
+ const { payload } = decodeJWT(currentSession.access_token);
1135
+ if (payload.exp) {
1136
+ expiresAt = payload.exp;
1137
+ hasExpired = expiresAt <= timeNow;
1138
+ }
1139
+ if (hasExpired) {
1140
+ const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token);
1141
+ if (error) {
1142
+ return { data: { user: null, session: null }, error: error };
1143
+ }
1144
+ if (!refreshedSession) {
1145
+ return { data: { user: null, session: null }, error: null };
1146
+ }
1147
+ session = refreshedSession;
1148
+ }
1149
+ else {
1150
+ const { data, error } = await this._getUser(currentSession.access_token);
1151
+ if (error) {
1152
+ throw error;
1153
+ }
1154
+ session = {
1155
+ access_token: currentSession.access_token,
1156
+ refresh_token: currentSession.refresh_token,
1157
+ user: data.user,
1158
+ token_type: 'bearer',
1159
+ expires_in: expiresAt - timeNow,
1160
+ expires_at: expiresAt,
1161
+ };
1162
+ await this._saveSession(session);
1163
+ await this._notifyAllSubscribers('SIGNED_IN', session);
1164
+ }
1165
+ return { data: { user: session.user, session }, error: null };
1166
+ }
1167
+ catch (error) {
1168
+ if (isAuthError(error)) {
1169
+ return { data: { session: null, user: null }, error };
1170
+ }
1171
+ throw error;
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Returns a new session, regardless of expiry status.
1176
+ * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
1177
+ * If the current session's refresh token is invalid, an error will be thrown.
1178
+ * @param currentSession The current session. If passed in, it must contain a refresh token.
1179
+ */
1180
+ async refreshSession(currentSession) {
1181
+ await this.initializePromise;
1182
+ return await this._acquireLock(-1, async () => {
1183
+ return await this._refreshSession(currentSession);
1184
+ });
1185
+ }
1186
+ async _refreshSession(currentSession) {
1187
+ try {
1188
+ return await this._useSession(async (result) => {
1189
+ var _a;
1190
+ if (!currentSession) {
1191
+ const { data, error } = result;
1192
+ if (error) {
1193
+ throw error;
1194
+ }
1195
+ currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined;
1196
+ }
1197
+ if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
1198
+ throw new AuthSessionMissingError();
1199
+ }
1200
+ const { session, error } = await this._callRefreshToken(currentSession.refresh_token);
1201
+ if (error) {
1202
+ return { data: { user: null, session: null }, error: error };
1203
+ }
1204
+ if (!session) {
1205
+ return { data: { user: null, session: null }, error: null };
1206
+ }
1207
+ return { data: { user: session.user, session }, error: null };
1208
+ });
1209
+ }
1210
+ catch (error) {
1211
+ if (isAuthError(error)) {
1212
+ return { data: { user: null, session: null }, error };
1213
+ }
1214
+ throw error;
1215
+ }
1216
+ }
1217
+ /**
1218
+ * Gets the session data from a URL string
1219
+ */
1220
+ async _getSessionFromURL(params, callbackUrlType) {
1221
+ try {
1222
+ if (!isBrowser())
1223
+ throw new AuthImplicitGrantRedirectError('No browser detected.');
1224
+ // If there's an error in the URL, it doesn't matter what flow it is, we just return the error.
1225
+ if (params.error || params.error_description || params.error_code) {
1226
+ // The error class returned implies that the redirect is from an implicit grant flow
1227
+ // but it could also be from a redirect error from a PKCE flow.
1228
+ throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', {
1229
+ error: params.error || 'unspecified_error',
1230
+ code: params.error_code || 'unspecified_code',
1231
+ });
1232
+ }
1233
+ // Checks for mismatches between the flowType initialised in the client and the URL parameters
1234
+ switch (callbackUrlType) {
1235
+ case 'implicit':
1236
+ if (this.flowType === 'pkce') {
1237
+ throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.');
1238
+ }
1239
+ break;
1240
+ case 'pkce':
1241
+ if (this.flowType === 'implicit') {
1242
+ throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.');
1243
+ }
1244
+ break;
1245
+ default:
1246
+ // there's no mismatch so we continue
1247
+ }
1248
+ // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange
1249
+ if (callbackUrlType === 'pkce') {
1250
+ this._debug('#_initialize()', 'begin', 'is PKCE flow', true);
1251
+ if (!params.code)
1252
+ throw new AuthPKCEGrantCodeExchangeError('No code detected.');
1253
+ const { data, error } = await this._exchangeCodeForSession(params.code);
1254
+ if (error)
1255
+ throw error;
1256
+ const url = new URL(window.location.href);
1257
+ url.searchParams.delete('code');
1258
+ window.history.replaceState(window.history.state, '', url.toString());
1259
+ return { data: { session: data.session, redirectType: null }, error: null };
1260
+ }
1261
+ const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params;
1262
+ if (!access_token || !expires_in || !refresh_token || !token_type) {
1263
+ throw new AuthImplicitGrantRedirectError('No session defined in URL');
1264
+ }
1265
+ const timeNow = Math.round(Date.now() / 1000);
1266
+ const expiresIn = parseInt(expires_in);
1267
+ let expiresAt = timeNow + expiresIn;
1268
+ if (expires_at) {
1269
+ expiresAt = parseInt(expires_at);
1270
+ }
1271
+ const actuallyExpiresIn = expiresAt - timeNow;
1272
+ if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION_MS) {
1273
+ console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`);
1274
+ }
1275
+ const issuedAt = expiresAt - expiresIn;
1276
+ if (timeNow - issuedAt >= 120) {
1277
+ console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow);
1278
+ }
1279
+ else if (timeNow - issuedAt < 0) {
1280
+ console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow);
1281
+ }
1282
+ const { data, error } = await this._getUser(access_token);
1283
+ if (error)
1284
+ throw error;
1285
+ const session = {
1286
+ provider_token,
1287
+ provider_refresh_token,
1288
+ access_token,
1289
+ expires_in: expiresIn,
1290
+ expires_at: expiresAt,
1291
+ refresh_token,
1292
+ token_type,
1293
+ user: data.user,
1294
+ };
1295
+ // Remove tokens from URL
1296
+ window.location.hash = '';
1297
+ this._debug('#_getSessionFromURL()', 'clearing window.location.hash');
1298
+ return { data: { session, redirectType: params.type }, error: null };
1299
+ }
1300
+ catch (error) {
1301
+ if (isAuthError(error)) {
1302
+ return { data: { session: null, redirectType: null }, error };
1303
+ }
1304
+ throw error;
1305
+ }
1306
+ }
1307
+ /**
1308
+ * 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)
1309
+ */
1310
+ _isImplicitGrantCallback(params) {
1311
+ return Boolean(params.access_token || params.error_description);
1312
+ }
1313
+ /**
1314
+ * Checks if the current URL and backing storage contain parameters given by a PKCE flow
1315
+ */
1316
+ async _isPKCECallback(params) {
1317
+ const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1318
+ return !!(params.code && currentStorageContent);
1319
+ }
1320
+ /**
1321
+ * 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.
1322
+ *
1323
+ * 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)`.
1324
+ * 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.
1325
+ *
1326
+ * If using `others` scope, no `SIGNED_OUT` event is fired!
1327
+ */
1328
+ async signOut(options = { scope: 'global' }) {
1329
+ await this.initializePromise;
1330
+ return await this._acquireLock(-1, async () => {
1331
+ return await this._signOut(options);
1332
+ });
1333
+ }
1334
+ async _signOut({ scope } = { scope: 'global' }) {
1335
+ return await this._useSession(async (result) => {
1336
+ var _a;
1337
+ const { data, error: sessionError } = result;
1338
+ if (sessionError) {
1339
+ return { error: sessionError };
1340
+ }
1341
+ const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;
1342
+ if (accessToken) {
1343
+ const { error } = await this.admin.signOut(accessToken, scope);
1344
+ if (error) {
1345
+ // ignore 404s since user might not exist anymore
1346
+ // ignore 401s since an invalid or expired JWT should sign out the current session
1347
+ if (!(isAuthApiError(error) &&
1348
+ (error.status === 404 || error.status === 401 || error.status === 403))) {
1349
+ return { error };
1350
+ }
1351
+ }
1352
+ }
1353
+ if (scope !== 'others') {
1354
+ await this._removeSession();
1355
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1356
+ }
1357
+ return { error: null };
1358
+ });
1359
+ }
1360
+ /**
1361
+ * Receive a notification every time an auth event happens.
1362
+ * @param callback A callback function to be invoked when an auth event happens.
1363
+ */
1364
+ onAuthStateChange(callback) {
1365
+ const id = uuid();
1366
+ const subscription = {
1367
+ id,
1368
+ callback,
1369
+ unsubscribe: () => {
1370
+ this._debug('#unsubscribe()', 'state change callback with id removed', id);
1371
+ this.stateChangeEmitters.delete(id);
1372
+ },
1373
+ };
1374
+ this._debug('#onAuthStateChange()', 'registered callback with id', id);
1375
+ this.stateChangeEmitters.set(id, subscription);
1376
+ (async () => {
1377
+ await this.initializePromise;
1378
+ await this._acquireLock(-1, async () => {
1379
+ this._emitInitialSession(id);
1380
+ });
1381
+ })();
1382
+ return { data: { subscription } };
1383
+ }
1384
+ async _emitInitialSession(id) {
1385
+ return await this._useSession(async (result) => {
1386
+ var _a, _b;
1387
+ try {
1388
+ const { data: { session }, error, } = result;
1389
+ if (error)
1390
+ throw error;
1391
+ await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session));
1392
+ this._debug('INITIAL_SESSION', 'callback id', id, 'session', session);
1393
+ }
1394
+ catch (err) {
1395
+ await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null));
1396
+ this._debug('INITIAL_SESSION', 'callback id', id, 'error', err);
1397
+ console.error(err);
1398
+ }
1399
+ });
1400
+ }
1401
+ /**
1402
+ * Sends a password reset request to an email address. This method supports the PKCE flow.
1403
+ *
1404
+ * @param email The email address of the user.
1405
+ * @param options.redirectTo The URL to send the user to after they click the password reset link.
1406
+ * @param options.captchaToken Verification token received when the user completes the captcha on the site.
1407
+ */
1408
+ async resetPasswordForEmail(email, options = {}) {
1409
+ let codeChallenge = null;
1410
+ let codeChallengeMethod = null;
1411
+ if (this.flowType === 'pkce') {
1412
+ ;
1413
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey, true // isPasswordRecovery
1414
+ );
1415
+ }
1416
+ try {
1417
+ return await _request(this.fetch, 'POST', `${this.url}/recover`, {
1418
+ body: {
1419
+ email,
1420
+ code_challenge: codeChallenge,
1421
+ code_challenge_method: codeChallengeMethod,
1422
+ gotrue_meta_security: { captcha_token: options.captchaToken },
1423
+ },
1424
+ headers: this.headers,
1425
+ redirectTo: options.redirectTo,
1426
+ });
1427
+ }
1428
+ catch (error) {
1429
+ if (isAuthError(error)) {
1430
+ return { data: null, error };
1431
+ }
1432
+ throw error;
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Gets all the identities linked to a user.
1437
+ */
1438
+ async getUserIdentities() {
1439
+ var _a;
1440
+ try {
1441
+ const { data, error } = await this.getUser();
1442
+ if (error)
1443
+ throw error;
1444
+ return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null };
1445
+ }
1446
+ catch (error) {
1447
+ if (isAuthError(error)) {
1448
+ return { data: null, error };
1449
+ }
1450
+ throw error;
1451
+ }
1452
+ }
1453
+ /**
1454
+ * Links an oauth identity to an existing user.
1455
+ * This method supports the PKCE flow.
1456
+ */
1457
+ async linkIdentity(credentials) {
1458
+ var _a;
1459
+ try {
1460
+ const { data, error } = await this._useSession(async (result) => {
1461
+ var _a, _b, _c, _d, _e;
1462
+ const { data, error } = result;
1463
+ if (error)
1464
+ throw error;
1465
+ const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
1466
+ redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
1467
+ scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
1468
+ queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
1469
+ skipBrowserRedirect: true,
1470
+ });
1471
+ return await _request(this.fetch, 'GET', url, {
1472
+ headers: this.headers,
1473
+ jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined,
1474
+ });
1475
+ });
1476
+ if (error)
1477
+ throw error;
1478
+ if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) {
1479
+ window.location.assign(data === null || data === void 0 ? void 0 : data.url);
1480
+ }
1481
+ return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null };
1482
+ }
1483
+ catch (error) {
1484
+ if (isAuthError(error)) {
1485
+ return { data: { provider: credentials.provider, url: null }, error };
1486
+ }
1487
+ throw error;
1488
+ }
1489
+ }
1490
+ /**
1491
+ * 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.
1492
+ */
1493
+ async unlinkIdentity(identity) {
1494
+ try {
1495
+ return await this._useSession(async (result) => {
1496
+ var _a, _b;
1497
+ const { data, error } = result;
1498
+ if (error) {
1499
+ throw error;
1500
+ }
1501
+ return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, {
1502
+ headers: this.headers,
1503
+ jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined,
1504
+ });
1505
+ });
1506
+ }
1507
+ catch (error) {
1508
+ if (isAuthError(error)) {
1509
+ return { data: null, error };
1510
+ }
1511
+ throw error;
1512
+ }
1513
+ }
1514
+ /**
1515
+ * Generates a new JWT.
1516
+ * @param refreshToken A valid refresh token that was returned on login.
1517
+ */
1518
+ async _refreshAccessToken(refreshToken) {
1519
+ const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`;
1520
+ this._debug(debugName, 'begin');
1521
+ try {
1522
+ const startedAt = Date.now();
1523
+ // will attempt to refresh the token with exponential backoff
1524
+ return await retryable(async (attempt) => {
1525
+ if (attempt > 0) {
1526
+ await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ...
1527
+ }
1528
+ this._debug(debugName, 'refreshing attempt', attempt);
1529
+ return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {
1530
+ body: { refresh_token: refreshToken },
1531
+ headers: this.headers,
1532
+ xform: _sessionResponse,
1533
+ });
1534
+ }, (attempt, error) => {
1535
+ const nextBackOffInterval = 200 * Math.pow(2, attempt);
1536
+ return (error &&
1537
+ isAuthRetryableFetchError(error) &&
1538
+ // retryable only if the request can be sent before the backoff overflows the tick duration
1539
+ Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION_MS);
1540
+ });
1541
+ }
1542
+ catch (error) {
1543
+ this._debug(debugName, 'error', error);
1544
+ if (isAuthError(error)) {
1545
+ return { data: { session: null, user: null }, error };
1546
+ }
1547
+ throw error;
1548
+ }
1549
+ finally {
1550
+ this._debug(debugName, 'end');
1551
+ }
1552
+ }
1553
+ _isValidSession(maybeSession) {
1554
+ const isValidSession = typeof maybeSession === 'object' &&
1555
+ maybeSession !== null &&
1556
+ 'access_token' in maybeSession &&
1557
+ 'refresh_token' in maybeSession &&
1558
+ 'expires_at' in maybeSession;
1559
+ return isValidSession;
1560
+ }
1561
+ async _handleProviderSignIn(provider, options) {
1562
+ const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, {
1563
+ redirectTo: options.redirectTo,
1564
+ scopes: options.scopes,
1565
+ queryParams: options.queryParams,
1566
+ });
1567
+ this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url);
1568
+ // try to open on the browser
1569
+ if (isBrowser() && !options.skipBrowserRedirect) {
1570
+ window.location.assign(url);
1571
+ }
1572
+ return { data: { provider, url }, error: null };
1573
+ }
1574
+ /**
1575
+ * Recovers the session from LocalStorage and refreshes the token
1576
+ * Note: this method is async to accommodate for AsyncStorage e.g. in React native.
1577
+ */
1578
+ async _recoverAndRefresh() {
1579
+ var _a;
1580
+ const debugName = '#_recoverAndRefresh()';
1581
+ this._debug(debugName, 'begin');
1582
+ try {
1583
+ const currentSession = await getItemAsync(this.storage, this.storageKey);
1584
+ this._debug(debugName, 'session from storage', currentSession);
1585
+ if (!this._isValidSession(currentSession)) {
1586
+ this._debug(debugName, 'session is not valid');
1587
+ if (currentSession !== null) {
1588
+ await this._removeSession();
1589
+ }
1590
+ return;
1591
+ }
1592
+ const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) * 1000 - Date.now() < EXPIRY_MARGIN_MS;
1593
+ this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s`);
1594
+ if (expiresWithMargin) {
1595
+ if (this.autoRefreshToken && currentSession.refresh_token) {
1596
+ const { error } = await this._callRefreshToken(currentSession.refresh_token);
1597
+ if (error) {
1598
+ console.error(error);
1599
+ if (!isAuthRetryableFetchError(error)) {
1600
+ this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error);
1601
+ await this._removeSession();
1602
+ }
1603
+ }
1604
+ }
1605
+ }
1606
+ else {
1607
+ // no need to persist currentSession again, as we just loaded it from
1608
+ // local storage; persisting it again may overwrite a value saved by
1609
+ // another client with access to the same local storage
1610
+ await this._notifyAllSubscribers('SIGNED_IN', currentSession);
1611
+ }
1612
+ }
1613
+ catch (err) {
1614
+ this._debug(debugName, 'error', err);
1615
+ console.error(err);
1616
+ return;
1617
+ }
1618
+ finally {
1619
+ this._debug(debugName, 'end');
1620
+ }
1621
+ }
1622
+ async _callRefreshToken(refreshToken) {
1623
+ var _a, _b;
1624
+ if (!refreshToken) {
1625
+ throw new AuthSessionMissingError();
1626
+ }
1627
+ // refreshing is already in progress
1628
+ if (this.refreshingDeferred) {
1629
+ return this.refreshingDeferred.promise;
1630
+ }
1631
+ const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`;
1632
+ this._debug(debugName, 'begin');
1633
+ try {
1634
+ this.refreshingDeferred = new Deferred();
1635
+ const { data, error } = await this._refreshAccessToken(refreshToken);
1636
+ if (error)
1637
+ throw error;
1638
+ if (!data.session)
1639
+ throw new AuthSessionMissingError();
1640
+ await this._saveSession(data.session);
1641
+ await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session);
1642
+ const result = { session: data.session, error: null };
1643
+ this.refreshingDeferred.resolve(result);
1644
+ return result;
1645
+ }
1646
+ catch (error) {
1647
+ this._debug(debugName, 'error', error);
1648
+ if (isAuthError(error)) {
1649
+ const result = { session: null, error };
1650
+ if (!isAuthRetryableFetchError(error)) {
1651
+ await this._removeSession();
1652
+ }
1653
+ (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result);
1654
+ return result;
1655
+ }
1656
+ (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error);
1657
+ throw error;
1658
+ }
1659
+ finally {
1660
+ this.refreshingDeferred = null;
1661
+ this._debug(debugName, 'end');
1662
+ }
1663
+ }
1664
+ async _notifyAllSubscribers(event, session, broadcast = true) {
1665
+ const debugName = `#_notifyAllSubscribers(${event})`;
1666
+ this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`);
1667
+ try {
1668
+ if (this.broadcastChannel && broadcast) {
1669
+ this.broadcastChannel.postMessage({ event, session });
1670
+ }
1671
+ const errors = [];
1672
+ const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {
1673
+ try {
1674
+ await x.callback(event, session);
1675
+ }
1676
+ catch (e) {
1677
+ errors.push(e);
1678
+ }
1679
+ });
1680
+ await Promise.all(promises);
1681
+ if (errors.length > 0) {
1682
+ for (let i = 0; i < errors.length; i += 1) {
1683
+ console.error(errors[i]);
1684
+ }
1685
+ throw errors[0];
1686
+ }
1687
+ }
1688
+ finally {
1689
+ this._debug(debugName, 'end');
1690
+ }
1691
+ }
1692
+ /**
1693
+ * set currentSession and currentUser
1694
+ * process to _startAutoRefreshToken if possible
1695
+ */
1696
+ async _saveSession(session) {
1697
+ this._debug('#_saveSession()', session);
1698
+ // _saveSession is always called whenever a new session has been acquired
1699
+ // so we can safely suppress the warning returned by future getSession calls
1700
+ this.suppressGetSessionWarning = true;
1701
+ await setItemAsync(this.storage, this.storageKey, session);
1702
+ }
1703
+ async _removeSession() {
1704
+ this._debug('#_removeSession()');
1705
+ await removeItemAsync(this.storage, this.storageKey);
1706
+ await this._notifyAllSubscribers('SIGNED_OUT', null);
1707
+ }
1708
+ /**
1709
+ * Removes any registered visibilitychange callback.
1710
+ *
1711
+ * {@see #startAutoRefresh}
1712
+ * {@see #stopAutoRefresh}
1713
+ */
1714
+ _removeVisibilityChangedCallback() {
1715
+ this._debug('#_removeVisibilityChangedCallback()');
1716
+ const callback = this.visibilityChangedCallback;
1717
+ this.visibilityChangedCallback = null;
1718
+ try {
1719
+ if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) {
1720
+ window.removeEventListener('visibilitychange', callback);
1721
+ }
1722
+ }
1723
+ catch (e) {
1724
+ console.error('removing visibilitychange callback failed', e);
1725
+ }
1726
+ }
1727
+ /**
1728
+ * This is the private implementation of {@link #startAutoRefresh}. Use this
1729
+ * within the library.
1730
+ */
1731
+ async _startAutoRefresh() {
1732
+ await this._stopAutoRefresh();
1733
+ this._debug('#_startAutoRefresh()');
1734
+ const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS);
1735
+ this.autoRefreshTicker = ticker;
1736
+ if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') {
1737
+ // ticker is a NodeJS Timeout object that has an `unref` method
1738
+ // https://nodejs.org/api/timers.html#timeoutunref
1739
+ // When auto refresh is used in NodeJS (like for testing) the
1740
+ // `setInterval` is preventing the process from being marked as
1741
+ // finished and tests run endlessly. This can be prevented by calling
1742
+ // `unref()` on the returned object.
1743
+ ticker.unref();
1744
+ // @ts-expect-error TS has no context of Deno
1745
+ }
1746
+ else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {
1747
+ // similar like for NodeJS, but with the Deno API
1748
+ // https://deno.land/api@latest?unstable&s=Deno.unrefTimer
1749
+ // @ts-expect-error TS has no context of Deno
1750
+ Deno.unrefTimer(ticker);
1751
+ }
1752
+ // run the tick immediately, but in the next pass of the event loop so that
1753
+ // #_initialize can be allowed to complete without recursively waiting on
1754
+ // itself
1755
+ setTimeout(async () => {
1756
+ await this.initializePromise;
1757
+ await this._autoRefreshTokenTick();
1758
+ }, 0);
1759
+ }
1760
+ /**
1761
+ * This is the private implementation of {@link #stopAutoRefresh}. Use this
1762
+ * within the library.
1763
+ */
1764
+ async _stopAutoRefresh() {
1765
+ this._debug('#_stopAutoRefresh()');
1766
+ const ticker = this.autoRefreshTicker;
1767
+ this.autoRefreshTicker = null;
1768
+ if (ticker) {
1769
+ clearInterval(ticker);
1770
+ }
1771
+ }
1772
+ /**
1773
+ * Starts an auto-refresh process in the background. The session is checked
1774
+ * every few seconds. Close to the time of expiration a process is started to
1775
+ * refresh the session. If refreshing fails it will be retried for as long as
1776
+ * necessary.
1777
+ *
1778
+ * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
1779
+ * to call this function, it will be called for you.
1780
+ *
1781
+ * On browsers the refresh process works only when the tab/window is in the
1782
+ * foreground to conserve resources as well as prevent race conditions and
1783
+ * flooding auth with requests. If you call this method any managed
1784
+ * visibility change callback will be removed and you must manage visibility
1785
+ * changes on your own.
1786
+ *
1787
+ * On non-browser platforms the refresh process works *continuously* in the
1788
+ * background, which may not be desirable. You should hook into your
1789
+ * platform's foreground indication mechanism and call these methods
1790
+ * appropriately to conserve resources.
1791
+ *
1792
+ * {@see #stopAutoRefresh}
1793
+ */
1794
+ async startAutoRefresh() {
1795
+ this._removeVisibilityChangedCallback();
1796
+ await this._startAutoRefresh();
1797
+ }
1798
+ /**
1799
+ * Stops an active auto refresh process running in the background (if any).
1800
+ *
1801
+ * If you call this method any managed visibility change callback will be
1802
+ * removed and you must manage visibility changes on your own.
1803
+ *
1804
+ * See {@link #startAutoRefresh} for more details.
1805
+ */
1806
+ async stopAutoRefresh() {
1807
+ this._removeVisibilityChangedCallback();
1808
+ await this._stopAutoRefresh();
1809
+ }
1810
+ /**
1811
+ * Runs the auto refresh token tick.
1812
+ */
1813
+ async _autoRefreshTokenTick() {
1814
+ this._debug('#_autoRefreshTokenTick()', 'begin');
1815
+ try {
1816
+ await this._acquireLock(0, async () => {
1817
+ try {
1818
+ const now = Date.now();
1819
+ try {
1820
+ return await this._useSession(async (result) => {
1821
+ const { data: { session }, } = result;
1822
+ if (!session || !session.refresh_token || !session.expires_at) {
1823
+ this._debug('#_autoRefreshTokenTick()', 'no session');
1824
+ return;
1825
+ }
1826
+ // session will expire in this many ticks (or has already expired if <= 0)
1827
+ const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS);
1828
+ 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`);
1829
+ if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {
1830
+ await this._callRefreshToken(session.refresh_token);
1831
+ }
1832
+ });
1833
+ }
1834
+ catch (e) {
1835
+ console.error('Auto refresh tick failed with error. This is likely a transient error.', e);
1836
+ }
1837
+ }
1838
+ finally {
1839
+ this._debug('#_autoRefreshTokenTick()', 'end');
1840
+ }
1841
+ });
1842
+ }
1843
+ catch (e) {
1844
+ if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) {
1845
+ this._debug('auto refresh token tick lock not available');
1846
+ }
1847
+ else {
1848
+ throw e;
1849
+ }
1850
+ }
1851
+ }
1852
+ /**
1853
+ * Registers callbacks on the browser / platform, which in-turn run
1854
+ * algorithms when the browser window/tab are in foreground. On non-browser
1855
+ * platforms it assumes always foreground.
1856
+ */
1857
+ async _handleVisibilityChange() {
1858
+ this._debug('#_handleVisibilityChange()');
1859
+ if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
1860
+ if (this.autoRefreshToken) {
1861
+ // in non-browser environments the refresh token ticker runs always
1862
+ this.startAutoRefresh();
1863
+ }
1864
+ return false;
1865
+ }
1866
+ try {
1867
+ this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false);
1868
+ window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback);
1869
+ // now immediately call the visbility changed callback to setup with the
1870
+ // current visbility state
1871
+ await this._onVisibilityChanged(true); // initial call
1872
+ }
1873
+ catch (error) {
1874
+ console.error('_handleVisibilityChange', error);
1875
+ }
1876
+ }
1877
+ /**
1878
+ * Callback registered with `window.addEventListener('visibilitychange')`.
1879
+ */
1880
+ async _onVisibilityChanged(calledFromInitialize) {
1881
+ const methodName = `#_onVisibilityChanged(${calledFromInitialize})`;
1882
+ this._debug(methodName, 'visibilityState', document.visibilityState);
1883
+ if (document.visibilityState === 'visible') {
1884
+ if (this.autoRefreshToken) {
1885
+ // in browser environments the refresh token ticker runs only on focused tabs
1886
+ // which prevents race conditions
1887
+ this._startAutoRefresh();
1888
+ }
1889
+ if (!calledFromInitialize) {
1890
+ // called when the visibility has changed, i.e. the browser
1891
+ // transitioned from hidden -> visible so we need to see if the session
1892
+ // should be recovered immediately... but to do that we need to acquire
1893
+ // the lock first asynchronously
1894
+ await this.initializePromise;
1895
+ await this._acquireLock(-1, async () => {
1896
+ if (document.visibilityState !== 'visible') {
1897
+ this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting');
1898
+ // visibility has changed while waiting for the lock, abort
1899
+ return;
1900
+ }
1901
+ // recover the session
1902
+ await this._recoverAndRefresh();
1903
+ });
1904
+ }
1905
+ }
1906
+ else if (document.visibilityState === 'hidden') {
1907
+ if (this.autoRefreshToken) {
1908
+ this._stopAutoRefresh();
1909
+ }
1910
+ }
1911
+ }
1912
+ /**
1913
+ * Generates the relevant login URL for a third-party provider.
1914
+ * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
1915
+ * @param options.scopes A space-separated list of scopes granted to the OAuth application.
1916
+ * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
1917
+ */
1918
+ async _getUrlForProvider(url, provider, options) {
1919
+ const urlParams = [`provider=${encodeURIComponent(provider)}`];
1920
+ if (options === null || options === void 0 ? void 0 : options.redirectTo) {
1921
+ urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`);
1922
+ }
1923
+ if (options === null || options === void 0 ? void 0 : options.scopes) {
1924
+ urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`);
1925
+ }
1926
+ if (this.flowType === 'pkce') {
1927
+ const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
1928
+ const flowParams = new URLSearchParams({
1929
+ code_challenge: `${encodeURIComponent(codeChallenge)}`,
1930
+ code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,
1931
+ });
1932
+ urlParams.push(flowParams.toString());
1933
+ }
1934
+ if (options === null || options === void 0 ? void 0 : options.queryParams) {
1935
+ const query = new URLSearchParams(options.queryParams);
1936
+ urlParams.push(query.toString());
1937
+ }
1938
+ if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) {
1939
+ urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`);
1940
+ }
1941
+ return `${url}?${urlParams.join('&')}`;
1942
+ }
1943
+ async _unenroll(params) {
1944
+ try {
1945
+ return await this._useSession(async (result) => {
1946
+ var _a;
1947
+ const { data: sessionData, error: sessionError } = result;
1948
+ if (sessionError) {
1949
+ return { data: null, error: sessionError };
1950
+ }
1951
+ return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {
1952
+ headers: this.headers,
1953
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
1954
+ });
1955
+ });
1956
+ }
1957
+ catch (error) {
1958
+ if (isAuthError(error)) {
1959
+ return { data: null, error };
1960
+ }
1961
+ throw error;
1962
+ }
1963
+ }
1964
+ async _enroll(params) {
1965
+ try {
1966
+ return await this._useSession(async (result) => {
1967
+ var _a, _b;
1968
+ const { data: sessionData, error: sessionError } = result;
1969
+ if (sessionError) {
1970
+ return { data: null, error: sessionError };
1971
+ }
1972
+ const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' ? { phone: params.phone } : { issuer: params.issuer }));
1973
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, {
1974
+ body,
1975
+ headers: this.headers,
1976
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
1977
+ });
1978
+ if (error) {
1979
+ return { data: null, error };
1980
+ }
1981
+ if (params.factorType === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) {
1982
+ data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`;
1983
+ }
1984
+ return { data, error: null };
1985
+ });
1986
+ }
1987
+ catch (error) {
1988
+ if (isAuthError(error)) {
1989
+ return { data: null, error };
1990
+ }
1991
+ throw error;
1992
+ }
1993
+ }
1994
+ /**
1995
+ * {@see GoTrueMFAApi#verify}
1996
+ */
1997
+ async _verify(params) {
1998
+ return this._acquireLock(-1, async () => {
1999
+ try {
2000
+ return await this._useSession(async (result) => {
2001
+ var _a;
2002
+ const { data: sessionData, error: sessionError } = result;
2003
+ if (sessionError) {
2004
+ return { data: null, error: sessionError };
2005
+ }
2006
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, {
2007
+ body: { code: params.code, challenge_id: params.challengeId },
2008
+ headers: this.headers,
2009
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2010
+ });
2011
+ if (error) {
2012
+ return { data: null, error };
2013
+ }
2014
+ await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data));
2015
+ await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data);
2016
+ return { data, error };
2017
+ });
2018
+ }
2019
+ catch (error) {
2020
+ if (isAuthError(error)) {
2021
+ return { data: null, error };
2022
+ }
2023
+ throw error;
2024
+ }
2025
+ });
2026
+ }
2027
+ /**
2028
+ * {@see GoTrueMFAApi#challenge}
2029
+ */
2030
+ async _challenge(params) {
2031
+ return this._acquireLock(-1, async () => {
2032
+ try {
2033
+ return await this._useSession(async (result) => {
2034
+ var _a;
2035
+ const { data: sessionData, error: sessionError } = result;
2036
+ if (sessionError) {
2037
+ return { data: null, error: sessionError };
2038
+ }
2039
+ return await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, {
2040
+ body: { channel: params.channel },
2041
+ headers: this.headers,
2042
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2043
+ });
2044
+ });
2045
+ }
2046
+ catch (error) {
2047
+ if (isAuthError(error)) {
2048
+ return { data: null, error };
2049
+ }
2050
+ throw error;
2051
+ }
2052
+ });
2053
+ }
2054
+ /**
2055
+ * {@see GoTrueMFAApi#challengeAndVerify}
2056
+ */
2057
+ async _challengeAndVerify(params) {
2058
+ // both _challenge and _verify independently acquire the lock, so no need
2059
+ // to acquire it here
2060
+ const { data: challengeData, error: challengeError } = await this._challenge({
2061
+ factorId: params.factorId,
2062
+ });
2063
+ if (challengeError) {
2064
+ return { data: null, error: challengeError };
2065
+ }
2066
+ return await this._verify({
2067
+ factorId: params.factorId,
2068
+ challengeId: challengeData.id,
2069
+ code: params.code,
2070
+ });
2071
+ }
2072
+ /**
2073
+ * {@see GoTrueMFAApi#listFactors}
2074
+ */
2075
+ async _listFactors() {
2076
+ // use #getUser instead of #_getUser as the former acquires a lock
2077
+ const { data: { user }, error: userError, } = await this.getUser();
2078
+ if (userError) {
2079
+ return { data: null, error: userError };
2080
+ }
2081
+ const factors = (user === null || user === void 0 ? void 0 : user.factors) || [];
2082
+ const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified');
2083
+ const phone = factors.filter((factor) => factor.factor_type === 'phone' && factor.status === 'verified');
2084
+ return {
2085
+ data: {
2086
+ all: factors,
2087
+ totp,
2088
+ phone,
2089
+ },
2090
+ error: null,
2091
+ };
2092
+ }
2093
+ /**
2094
+ * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
2095
+ */
2096
+ async _getAuthenticatorAssuranceLevel() {
2097
+ return this._acquireLock(-1, async () => {
2098
+ return await this._useSession(async (result) => {
2099
+ var _a, _b;
2100
+ const { data: { session }, error: sessionError, } = result;
2101
+ if (sessionError) {
2102
+ return { data: null, error: sessionError };
2103
+ }
2104
+ if (!session) {
2105
+ return {
2106
+ data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },
2107
+ error: null,
2108
+ };
2109
+ }
2110
+ const { payload } = decodeJWT(session.access_token);
2111
+ let currentLevel = null;
2112
+ if (payload.aal) {
2113
+ currentLevel = payload.aal;
2114
+ }
2115
+ let nextLevel = currentLevel;
2116
+ const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : [];
2117
+ if (verifiedFactors.length > 0) {
2118
+ nextLevel = 'aal2';
2119
+ }
2120
+ const currentAuthenticationMethods = payload.amr || [];
2121
+ return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };
2122
+ });
2123
+ });
2124
+ }
2125
+ async fetchJwk(kid, jwks = { keys: [] }) {
2126
+ // try fetching from the supplied jwks
2127
+ let jwk = jwks.keys.find((key) => key.kid === kid);
2128
+ if (jwk) {
2129
+ return jwk;
2130
+ }
2131
+ // try fetching from cache
2132
+ jwk = this.jwks.keys.find((key) => key.kid === kid);
2133
+ // jwk exists and jwks isn't stale
2134
+ if (jwk && this.jwks_cached_at + JWKS_TTL > Date.now()) {
2135
+ return jwk;
2136
+ }
2137
+ // jwk isn't cached in memory so we need to fetch it from the well-known endpoint
2138
+ const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, {
2139
+ headers: this.headers,
2140
+ });
2141
+ if (error) {
2142
+ throw error;
2143
+ }
2144
+ if (!data.keys || data.keys.length === 0) {
2145
+ throw new AuthInvalidJwtError('JWKS is empty');
2146
+ }
2147
+ this.jwks = data;
2148
+ this.jwks_cached_at = Date.now();
2149
+ // Find the signing key
2150
+ jwk = data.keys.find((key) => key.kid === kid);
2151
+ if (!jwk) {
2152
+ throw new AuthInvalidJwtError('No matching signing key found in JWKS');
2153
+ }
2154
+ return jwk;
2155
+ }
2156
+ /**
2157
+ * @experimental This method may change in future versions.
2158
+ * @description Gets the claims from a JWT. If the JWT is symmetric JWTs, it will call getUser() to verify against the server. If the JWT is asymmetric, it will be verified against the JWKS using the WebCrypto API.
2159
+ */
2160
+ async getClaims(jwt, jwks = { keys: [] }) {
2161
+ try {
2162
+ let token = jwt;
2163
+ if (!token) {
2164
+ const { data, error } = await this.getSession();
2165
+ if (error || !data.session) {
2166
+ return { data: null, error };
2167
+ }
2168
+ token = data.session.access_token;
2169
+ }
2170
+ const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = decodeJWT(token);
2171
+ // Reject expired JWTs
2172
+ validateExp(payload.exp);
2173
+ // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser()
2174
+ if (!header.kid ||
2175
+ header.alg === 'HS256' ||
2176
+ !('crypto' in globalThis && 'subtle' in globalThis.crypto)) {
2177
+ const { error } = await this.getUser(token);
2178
+ if (error) {
2179
+ throw error;
2180
+ }
2181
+ // getUser succeeds so the claims in the JWT can be trusted
2182
+ return {
2183
+ data: {
2184
+ claims: payload,
2185
+ header,
2186
+ signature,
2187
+ },
2188
+ error: null,
2189
+ };
2190
+ }
2191
+ const algorithm = getAlgorithm(header.alg);
2192
+ const signingKey = await this.fetchJwk(header.kid, jwks);
2193
+ // Convert JWK to CryptoKey
2194
+ const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [
2195
+ 'verify',
2196
+ ]);
2197
+ // Verify the signature
2198
+ const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, stringToUint8Array(`${rawHeader}.${rawPayload}`));
2199
+ if (!isValid) {
2200
+ throw new AuthInvalidJwtError('Invalid JWT signature');
2201
+ }
2202
+ // If verification succeeds, decode and return claims
2203
+ return {
2204
+ data: {
2205
+ claims: payload,
2206
+ header,
2207
+ signature,
2208
+ },
2209
+ error: null,
2210
+ };
2211
+ }
2212
+ catch (error) {
2213
+ if (isAuthError(error)) {
2214
+ return { data: null, error };
2215
+ }
2216
+ throw error;
2217
+ }
2218
+ }
2219
+ }
2220
+ GoTrueClient.nextInstanceID = 0;
2221
+ //# sourceMappingURL=GoTrueClient.js.map