UNPKG

@supabase/auth-js

Version:

Official client library for Supabase Auth

1,015 lines (1,014 loc) 117 kB
import GoTrueAdminApi from './GoTrueAdminApi'; import { DEFAULT_HEADERS, EXPIRY_MARGIN_MS, AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, GOTRUE_URL, STORAGE_KEY, JWKS_TTL, } from './lib/constants'; import { AuthImplicitGrantRedirectError, AuthPKCEGrantCodeExchangeError, AuthInvalidCredentialsError, AuthSessionMissingError, AuthInvalidTokenResponseError, AuthUnknownError, isAuthApiError, isAuthError, isAuthRetryableFetchError, isAuthSessionMissingError, isAuthImplicitGrantRedirectError, AuthInvalidJwtError, } from './lib/errors'; import { _request, _sessionResponse, _sessionResponsePassword, _userResponse, _ssoResponse, } from './lib/fetch'; import { deepClone, Deferred, getItemAsync, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, parseParametersFromURL, getCodeChallengeAndMethod, getAlgorithm, validateExp, decodeJWT, userNotAvailableProxy, supportsLocalStorage, } from './lib/helpers'; import { memoryLocalStorageAdapter } from './lib/local-storage'; import { polyfillGlobalThis } from './lib/polyfills'; import { version } from './lib/version'; import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'; import { stringToUint8Array, bytesToBase64URL } from './lib/base64url'; import { fromHex, getAddress, toHex, createSiweMessage, } from './lib/web3/ethereum'; polyfillGlobalThis(); // Make "globalThis" available const DEFAULT_OPTIONS = { url: GOTRUE_URL, storageKey: STORAGE_KEY, autoRefreshToken: true, persistSession: true, detectSessionInUrl: true, headers: DEFAULT_HEADERS, flowType: 'implicit', debug: false, hasCustomAuthorizationHeader: false, }; async function lockNoOp(name, acquireTimeout, fn) { return await fn(); } /** * Caches JWKS values for all clients created in the same environment. This is * especially useful for shared-memory execution environments such as Vercel's * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how * many clients are created, if they share the same storage key they will use * the same JWKS cache, significantly speeding up getClaims() with asymmetric * JWTs. */ const GLOBAL_JWKS = {}; export default class GoTrueClient { /** * Create a new client for use in the browser. */ constructor(options) { var _a, _b; /** * @experimental */ this.userStorage = null; this.memoryStorage = null; this.stateChangeEmitters = new Map(); this.autoRefreshTicker = null; this.visibilityChangedCallback = null; this.refreshingDeferred = null; /** * Keeps track of the async client initialization. * When null or not yet resolved the auth state is `unknown` * Once resolved the auth state is known and it's safe to call any further client methods. * Keep extra care to never reject or throw uncaught errors */ this.initializePromise = null; this.detectSessionInUrl = true; this.hasCustomAuthorizationHeader = false; this.suppressGetSessionWarning = false; this.lockAcquired = false; this.pendingInLock = []; /** * Used to broadcast state change events to other tabs listening. */ this.broadcastChannel = null; this.logger = console.log; this.instanceID = GoTrueClient.nextInstanceID; GoTrueClient.nextInstanceID += 1; if (this.instanceID > 0 && isBrowser()) { console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); } const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); this.logDebugMessages = !!settings.debug; if (typeof settings.debug === 'function') { this.logger = settings.debug; } this.persistSession = settings.persistSession; this.storageKey = settings.storageKey; this.autoRefreshToken = settings.autoRefreshToken; this.admin = new GoTrueAdminApi({ url: settings.url, headers: settings.headers, fetch: settings.fetch, }); this.url = settings.url; this.headers = settings.headers; this.fetch = resolveFetch(settings.fetch); this.lock = settings.lock || lockNoOp; this.detectSessionInUrl = settings.detectSessionInUrl; this.flowType = settings.flowType; this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; if (settings.lock) { this.lock = settings.lock; } else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) { this.lock = navigatorLock; } else { this.lock = lockNoOp; } if (!this.jwks) { this.jwks = { keys: [] }; this.jwks_cached_at = Number.MIN_SAFE_INTEGER; } this.mfa = { verify: this._verify.bind(this), enroll: this._enroll.bind(this), unenroll: this._unenroll.bind(this), challenge: this._challenge.bind(this), listFactors: this._listFactors.bind(this), challengeAndVerify: this._challengeAndVerify.bind(this), getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), }; if (this.persistSession) { if (settings.storage) { this.storage = settings.storage; } else { if (supportsLocalStorage()) { this.storage = globalThis.localStorage; } else { this.memoryStorage = {}; this.storage = memoryLocalStorageAdapter(this.memoryStorage); } } if (settings.userStorage) { this.userStorage = settings.userStorage; } } else { this.memoryStorage = {}; this.storage = memoryLocalStorageAdapter(this.memoryStorage); } if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { try { this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); } catch (e) { console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); } (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => { this._debug('received broadcast notification from other tab or client', event); await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages }); } this.initialize(); } /** * The JWKS used for verifying asymmetric JWTs */ get jwks() { var _a, _b; return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; } set jwks(value) { GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); } get jwks_cached_at() { var _a, _b; return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; } set jwks_cached_at(value) { GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); } _debug(...args) { if (this.logDebugMessages) { this.logger(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args); } return this; } /** * Initializes the client session either from the url or from storage. * This method is automatically called when instantiating the client, but should also be called * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). */ async initialize() { if (this.initializePromise) { return await this.initializePromise; } this.initializePromise = (async () => { return await this._acquireLock(-1, async () => { return await this._initialize(); }); })(); return await this.initializePromise; } /** * IMPORTANT: * 1. Never throw in this method, as it is called from the constructor * 2. Never return a session from this method as it would be cached over * the whole lifetime of the client */ async _initialize() { var _a; try { const params = parseParametersFromURL(window.location.href); let callbackUrlType = 'none'; if (this._isImplicitGrantCallback(params)) { callbackUrlType = 'implicit'; } else if (await this._isPKCECallback(params)) { callbackUrlType = 'pkce'; } /** * Attempt to get the session from the URL only if these conditions are fulfilled * * Note: If the URL isn't one of the callback url types (implicit or pkce), * then there could be an existing session so we don't want to prematurely remove it */ if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') { const { data, error } = await this._getSessionFromURL(params, callbackUrlType); if (error) { this._debug('#_initialize()', 'error detecting session from URL', error); if (isAuthImplicitGrantRedirectError(error)) { const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; if (errorCode === 'identity_already_exists' || errorCode === 'identity_not_found' || errorCode === 'single_identity_not_deletable') { return { error }; } } // failed login attempt via url, // remove old session as in verifyOtp, signUp and signInWith* await this._removeSession(); return { error }; } const { session, redirectType } = data; this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); await this._saveSession(session); setTimeout(async () => { if (redirectType === 'recovery') { await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); } else { await this._notifyAllSubscribers('SIGNED_IN', session); } }, 0); return { error: null }; } // no login attempt via callback url try to recover session from storage await this._recoverAndRefresh(); return { error: null }; } catch (error) { if (isAuthError(error)) { return { error }; } return { error: new AuthUnknownError('Unexpected error during initialization', error), }; } finally { await this._handleVisibilityChange(); this._debug('#_initialize()', 'end'); } } /** * Creates a new anonymous user. * * @returns A session where the is_anonymous claim in the access token JWT set to true */ async signInAnonymously(credentials) { var _a, _b, _c; try { const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { headers: this.headers, body: { 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 : {}, gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, }, xform: _sessionResponse, }); const { data, error } = res; if (error || !data) { return { data: { user: null, session: null }, error: error }; } const session = data.session; const user = data.user; if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', session); } return { data: { user, session }, error: null }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Creates a new user. * * Be aware that if a user account exists in the system you may get back an * error message that attempts to hide this information from the user. * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. * * @returns A logged-in session if the server has "autoconfirm" ON * @returns A user if the server has "autoconfirm" OFF */ async signUp(credentials) { var _a, _b, _c; try { let res; if ('email' in credentials) { const { email, password, options } = credentials; let codeChallenge = null; let codeChallengeMethod = null; if (this.flowType === 'pkce') { ; [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); } res = await _request(this.fetch, 'POST', `${this.url}/signup`, { headers: this.headers, redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, body: { email, password, data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod, }, xform: _sessionResponse, }); } else if ('phone' in credentials) { const { phone, password, options } = credentials; res = await _request(this.fetch, 'POST', `${this.url}/signup`, { headers: this.headers, body: { phone, password, data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, xform: _sessionResponse, }); } else { throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); } const { data, error } = res; if (error || !data) { return { data: { user: null, session: null }, error: error }; } const session = data.session; const user = data.user; if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', session); } return { data: { user, session }, error: null }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Log in an existing user with an email and password or phone and password. * * Be aware that you may get back an error message that will not distinguish * between the cases where the account does not exist or that the * email/phone and password combination is wrong or that the account can only * be accessed via social login. */ async signInWithPassword(credentials) { try { let res; if ('email' in credentials) { const { email, password, options } = credentials; res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { headers: this.headers, body: { email, password, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, xform: _sessionResponsePassword, }); } else if ('phone' in credentials) { const { phone, password, options } = credentials; res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { headers: this.headers, body: { phone, password, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, xform: _sessionResponsePassword, }); } else { throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); } const { data, error } = res; if (error) { return { data: { user: null, session: null }, error }; } else if (!data || !data.session || !data.user) { return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }; } if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', data.session); } return { data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), error, }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Log in an existing user via a third-party provider. * This method supports the PKCE flow. */ async signInWithOAuth(credentials) { var _a, _b, _c, _d; return await this._handleProviderSignIn(credentials.provider, { redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, }); } /** * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. */ async exchangeCodeForSession(authCode) { await this.initializePromise; return this._acquireLock(-1, async () => { return this._exchangeCodeForSession(authCode); }); } /** * Signs in a user by verifying a message signed by the user's private key. * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, * both of which derive from the EIP-4361 standard * With slight variation on Solana's side. * @reference https://eips.ethereum.org/EIPS/eip-4361 */ async signInWithWeb3(credentials) { const { chain } = credentials; switch (chain) { case 'ethereum': return await this.signInWithEthereum(credentials); case 'solana': return await this.signInWithSolana(credentials); default: throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); } } async signInWithEthereum(credentials) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; // TODO: flatten type let message; let signature; if ('message' in credentials) { message = credentials.message; signature = credentials.signature; } else { const { chain, wallet, statement, options } = credentials; let resolvedWallet; if (!isBrowser()) { if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); } resolvedWallet = wallet; } else if (typeof wallet === 'object') { resolvedWallet = wallet; } else { const windowAny = window; if ('ethereum' in windowAny && typeof windowAny.ethereum === 'object' && 'request' in windowAny.ethereum && typeof windowAny.ethereum.request === 'function') { resolvedWallet = windowAny.ethereum; } else { 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.`); } } const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); const accounts = await resolvedWallet .request({ method: 'eth_requestAccounts', }) .then((accs) => accs) .catch(() => { throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); }); if (!accounts || accounts.length === 0) { throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); } const address = getAddress(accounts[0]); let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; if (!chainId) { const chainIdHex = await resolvedWallet.request({ method: 'eth_chainId', }); chainId = fromHex(chainIdHex); } const siweMessage = { domain: url.host, address: address, statement: statement, uri: url.href, version: '1', chainId: chainId, nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, 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(), expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, }; message = createSiweMessage(siweMessage); // Sign message signature = (await resolvedWallet.request({ method: 'personal_sign', params: [toHex(message), address], })); } try { const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { headers: this.headers, body: Object.assign({ chain: 'ethereum', message, signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } : null)), xform: _sessionResponse, }); if (error) { throw error; } if (!data || !data.session || !data.user) { return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError(), }; } if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', data.session); } return { data: Object.assign({}, data), error }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } async signInWithSolana(credentials) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; let message; let signature; if ('message' in credentials) { message = credentials.message; signature = credentials.signature; } else { const { chain, wallet, statement, options } = credentials; let resolvedWallet; if (!isBrowser()) { if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); } resolvedWallet = wallet; } else if (typeof wallet === 'object') { resolvedWallet = wallet; } else { const windowAny = window; if ('solana' in windowAny && typeof windowAny.solana === 'object' && (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || ('signMessage' in windowAny.solana && typeof windowAny.solana.signMessage === 'function'))) { resolvedWallet = windowAny.solana; } else { 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.`); } } const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); if ('signIn' in resolvedWallet && resolvedWallet.signIn) { const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { // non-overridable properties version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); let outputToProcess; if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { outputToProcess = output[0]; } else if (output && typeof output === 'object' && 'signedMessage' in output && 'signature' in output) { outputToProcess = output; } else { throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); } if ('signedMessage' in outputToProcess && 'signature' in outputToProcess && (typeof outputToProcess.signedMessage === 'string' || outputToProcess.signedMessage instanceof Uint8Array) && outputToProcess.signature instanceof Uint8Array) { message = typeof outputToProcess.signedMessage === 'string' ? outputToProcess.signedMessage : new TextDecoder().decode(outputToProcess.signedMessage); signature = outputToProcess.signature; } else { throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); } } else { if (!('signMessage' in resolvedWallet) || typeof resolvedWallet.signMessage !== 'function' || !('publicKey' in resolvedWallet) || typeof resolvedWallet !== 'object' || !resolvedWallet.publicKey || !('toBase58' in resolvedWallet.publicKey) || typeof resolvedWallet.publicKey.toBase58 !== 'function') { throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); } message = [ `${url.host} wants you to sign in with your Solana account:`, resolvedWallet.publicKey.toBase58(), ...(statement ? ['', statement, ''] : ['']), 'Version: 1', `URI: ${url.href}`, `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()}`, ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) ? [`Not Before: ${options.signInWithSolana.notBefore}`] : []), ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : []), ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) ? [`Chain ID: ${options.signInWithSolana.chainId}`] : []), ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) ? [`Request ID: ${options.signInWithSolana.requestId}`] : []), ...(((_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) ? [ 'Resources', ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), ] : []), ].join('\n'); const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); } signature = maybeSignature; } } try { const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { headers: this.headers, body: Object.assign({ chain: 'solana', message, signature: bytesToBase64URL(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } : null)), xform: _sessionResponse, }); if (error) { throw error; } if (!data || !data.session || !data.user) { return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError(), }; } if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', data.session); } return { data: Object.assign({}, data), error }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } async _exchangeCodeForSession(authCode) { const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); try { const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { headers: this.headers, body: { auth_code: authCode, code_verifier: codeVerifier, }, xform: _sessionResponse, }); await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); if (error) { throw error; } if (!data || !data.session || !data.user) { return { data: { user: null, session: null, redirectType: null }, error: new AuthInvalidTokenResponseError(), }; } if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', data.session); } return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null, redirectType: null }, error }; } throw error; } } /** * Allows signing in with an OIDC ID token. The authentication provider used * should be enabled and configured. */ async signInWithIdToken(credentials) { try { const { options, provider, token, access_token, nonce } = credentials; const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { headers: this.headers, body: { provider, id_token: token, access_token, nonce, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, xform: _sessionResponse, }); const { data, error } = res; if (error) { return { data: { user: null, session: null }, error }; } else if (!data || !data.session || !data.user) { return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError(), }; } if (data.session) { await this._saveSession(data.session); await this._notifyAllSubscribers('SIGNED_IN', data.session); } return { data, error }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Log in a user using magiclink or a one-time password (OTP). * * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. * 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. * * Be aware that you may get back an error message that will not distinguish * between the cases where the account does not exist or, that the account * can only be accessed via social login. * * Do note that you will need to configure a Whatsapp sender on Twilio * if you are using phone sign in with the 'whatsapp' channel. The whatsapp * channel is not supported on other providers * at this time. * This method supports PKCE when an email is passed. */ async signInWithOtp(credentials) { var _a, _b, _c, _d, _e; try { if ('email' in credentials) { const { email, options } = credentials; let codeChallenge = null; let codeChallengeMethod = null; if (this.flowType === 'pkce') { ; [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); } const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { headers: this.headers, body: { email, data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod, }, redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, }); return { data: { user: null, session: null }, error }; } if ('phone' in credentials) { const { phone, options } = credentials; const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { headers: this.headers, body: { phone, data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', }, }); return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; } throw new AuthInvalidCredentialsError('You must provide either an email or phone number.'); } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Log in a user given a User supplied OTP or TokenHash received through mobile or email. */ async verifyOtp(params) { var _a, _b; try { let redirectTo = undefined; let captchaToken = undefined; if ('options' in params) { redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; } const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { headers: this.headers, body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), redirectTo, xform: _sessionResponse, }); if (error) { throw error; } if (!data) { throw new Error('An error occurred on token verification.'); } const session = data.session; const user = data.user; if (session === null || session === void 0 ? void 0 : session.access_token) { await this._saveSession(session); await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); } return { data: { user, session }, error: null }; } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Attempts a single-sign on using an enterprise Identity Provider. A * successful SSO attempt will redirect the current page to the identity * provider authorization page. The redirect URL is implementation and SSO * protocol specific. * * You can use it by providing a SSO domain. Typically you can extract this * domain by asking users for their email address. If this domain is * registered on the Auth instance the redirect will use that organization's * currently active SSO Identity Provider for the login. * * If you have built an organization-specific login page, you can use the * organization's SSO Identity Provider UUID directly instead. */ async signInWithSSO(params) { var _a, _b, _c; try { let codeChallenge = null; let codeChallengeMethod = null; if (this.flowType === 'pkce') { ; [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); } return await _request(this.fetch, 'POST', `${this.url}/sso`, { 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) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), headers: this.headers, xform: _ssoResponse, }); } catch (error) { if (isAuthError(error)) { return { data: null, error }; } throw error; } } /** * Sends a reauthentication OTP to the user's email or phone number. * Requires the user to be signed-in. */ async reauthenticate() { await this.initializePromise; return await this._acquireLock(-1, async () => { return await this._reauthenticate(); }); } async _reauthenticate() { try { return await this._useSession(async (result) => { const { data: { session }, error: sessionError, } = result; if (sessionError) throw sessionError; if (!session) throw new AuthSessionMissingError(); const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { headers: this.headers, jwt: session.access_token, }); return { data: { user: null, session: null }, error }; }); } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. */ async resend(credentials) { try { const endpoint = `${this.url}/resend`; if ('email' in credentials) { const { email, type, options } = credentials; const { error } = await _request(this.fetch, 'POST', endpoint, { headers: this.headers, body: { email, type, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, }); return { data: { user: null, session: null }, error }; } else if ('phone' in credentials) { const { phone, type, options } = credentials; const { data, error } = await _request(this.fetch, 'POST', endpoint, { headers: this.headers, body: { phone, type, gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, }, }); return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; } throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Returns the session, refreshing it if necessary. * * 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. * * **IMPORTANT:** This method loads values directly from the storage attached * to the client. If that storage is based on request cookies for example, * the values in it may not be authentic and therefore it's strongly advised * against using this method and its results in such circumstances. A warning * will be emitted if this is detected. Use {@link #getUser()} instead. */ async getSession() { await this.initializePromise;