@depup/supabase__auth-js 2.99.2-depup.0

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