UNPKG

@supabase/auth-js

Version:
1,591 lines (1,432 loc) 113 kB
import GoTrueAdminApi from './GoTrueAdminApi' import { AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, DEFAULT_HEADERS, EXPIRY_MARGIN_MS, GOTRUE_URL, JWKS_TTL, STORAGE_KEY, } from './lib/constants' import { AuthError, AuthImplicitGrantRedirectError, AuthInvalidCredentialsError, AuthInvalidJwtError, AuthInvalidTokenResponseError, AuthPKCEGrantCodeExchangeError, AuthSessionMissingError, AuthUnknownError, isAuthApiError, isAuthError, isAuthImplicitGrantRedirectError, isAuthRetryableFetchError, isAuthSessionMissingError, } from './lib/errors' import { Fetch, _request, _sessionResponse, _sessionResponsePassword, _ssoResponse, _userResponse, } from './lib/fetch' import { decodeJWT, deepClone, Deferred, getAlgorithm, getCodeChallengeAndMethod, getItemAsync, isBrowser, parseParametersFromURL, removeItemAsync, resolveFetch, retryable, setItemAsync, sleep, supportsLocalStorage, userNotAvailableProxy, uuid, validateExp, } from './lib/helpers' import { memoryLocalStorageAdapter } from './lib/local-storage' import { LockAcquireTimeoutError, navigatorLock } from './lib/locks' import { polyfillGlobalThis } from './lib/polyfills' import { version } from './lib/version' import { bytesToBase64URL, stringToUint8Array } from './lib/base64url' import type { AuthChangeEvent, AuthenticatorAssuranceLevels, AuthFlowType, AuthMFAChallengePhoneResponse, AuthMFAChallengeResponse, AuthMFAChallengeTOTPResponse, AuthMFAChallengeWebauthnResponse, AuthMFAChallengeWebauthnServerResponse, AuthMFAEnrollPhoneResponse, AuthMFAEnrollResponse, AuthMFAEnrollTOTPResponse, AuthMFAEnrollWebauthnResponse, AuthMFAGetAuthenticatorAssuranceLevelResponse, AuthMFAListFactorsResponse, AuthMFAUnenrollResponse, AuthMFAVerifyResponse, AuthOtpResponse, AuthResponse, AuthResponsePassword, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, EthereumWallet, EthereumWeb3Credentials, Factor, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, MFAChallengeAndVerifyParams, MFAChallengeParams, MFAChallengePhoneParams, MFAChallengeTOTPParams, MFAChallengeWebauthnParams, MFAEnrollParams, MFAEnrollPhoneParams, MFAEnrollTOTPParams, MFAEnrollWebauthnParams, MFAUnenrollParams, MFAVerifyParams, MFAVerifyPhoneParams, MFAVerifyTOTPParams, MFAVerifyWebauthnParamFields, MFAVerifyWebauthnParams, OAuthResponse, Prettify, Provider, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SolanaWallet, SolanaWeb3Credentials, SSOResponse, StrictOmit, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials, } from './lib/types' import { createSiweMessage, fromHex, getAddress, Hex, SiweMessage, toHex, } from './lib/web3/ethereum' import { deserializeCredentialCreationOptions, deserializeCredentialRequestOptions, serializeCredentialCreationResponse, serializeCredentialRequestResponse, WebAuthnApi, } from './lib/webauthn' import { AuthenticationCredential, PublicKeyCredentialJSON, RegistrationCredential, } from './lib/webauthn.dom' polyfillGlobalThis() // Make "globalThis" available const DEFAULT_OPTIONS: Omit< Required<GoTrueClientOptions>, 'fetch' | 'storage' | 'userStorage' | 'lock' > = { url: GOTRUE_URL, storageKey: STORAGE_KEY, autoRefreshToken: true, persistSession: true, detectSessionInUrl: true, headers: DEFAULT_HEADERS, flowType: 'implicit', debug: false, hasCustomAuthorizationHeader: false, } async function lockNoOp<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R> { 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: { [storageKey: string]: { cachedAt: number; jwks: { keys: JWK[] } } } = {} export default class GoTrueClient { private static nextInstanceID = 0 private instanceID: number /** * Namespace for the GoTrue admin methods. * These methods should only be used in a trusted server-side environment. */ admin: GoTrueAdminApi /** * Namespace for the MFA methods. */ mfa: GoTrueMFAApi /** * The storage key used to identify the values saved in localStorage */ protected storageKey: string protected flowType: AuthFlowType /** * The JWKS used for verifying asymmetric JWTs */ protected get jwks() { return GLOBAL_JWKS[this.storageKey]?.jwks ?? { keys: [] } } protected set jwks(value: { keys: JWK[] }) { GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], jwks: value } } protected get jwks_cached_at() { return GLOBAL_JWKS[this.storageKey]?.cachedAt ?? Number.MIN_SAFE_INTEGER } protected set jwks_cached_at(value: number) { GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], cachedAt: value } } protected autoRefreshToken: boolean protected persistSession: boolean protected storage: SupportedStorage /** * @experimental */ protected userStorage: SupportedStorage | null = null protected memoryStorage: { [key: string]: string } | null = null protected stateChangeEmitters: Map<string, Subscription> = new Map() protected autoRefreshTicker: ReturnType<typeof setInterval> | null = null protected visibilityChangedCallback: (() => Promise<any>) | null = null protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null = 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 */ protected initializePromise: Promise<InitializeResult> | null = null protected detectSessionInUrl = true protected url: string protected headers: { [key: string]: string } protected hasCustomAuthorizationHeader = false protected suppressGetSessionWarning = false protected fetch: Fetch protected lock: LockFunc protected lockAcquired = false protected pendingInLock: Promise<any>[] = [] /** * Used to broadcast state change events to other tabs listening. */ protected broadcastChannel: BroadcastChannel | null = null protected logDebugMessages: boolean protected logger: (message: string, ...args: any[]) => void = console.log /** * Create a new client for use in the browser. */ constructor(options: GoTrueClientOptions) { 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 = { ...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() && globalThis?.navigator?.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), webauthn: new WebAuthnApi(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: any) { console.error( 'Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e ) } this.broadcastChannel?.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() } private _debug(...args: any[]): GoTrueClient { 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(): Promise<InitializeResult> { 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 */ private async _initialize(): Promise<InitializeResult> { 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 = error.details?.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?: SignInAnonymouslyCredentials): Promise<AuthResponse> { try { const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { headers: this.headers, body: { data: credentials?.options?.data ?? {}, gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken }, }, xform: _sessionResponse, }) const { data, error } = res if (error || !data) { return { data: { user: null, session: null }, error: error } } const session: Session | null = data.session const user: User | null = 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: SignUpWithPasswordCredentials): Promise<AuthResponse> { try { let res: AuthResponse if ('email' in credentials) { const { email, password, options } = credentials let codeChallenge: string | null = null let codeChallengeMethod: string | null = 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?.emailRedirectTo, body: { email, password, data: options?.data ?? {}, gotrue_meta_security: { captcha_token: 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: options?.data ?? {}, channel: options?.channel ?? 'sms', gotrue_meta_security: { captcha_token: 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: Session | null = data.session const user: User | null = 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: SignInWithPasswordCredentials ): Promise<AuthTokenResponsePassword> { try { let res: AuthResponsePassword 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?.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?.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: { 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: SignInWithOAuthCredentials): Promise<OAuthResponse> { return await this._handleProviderSignIn(credentials.provider, { redirectTo: credentials.options?.redirectTo, scopes: credentials.options?.scopes, queryParams: credentials.options?.queryParams, skipBrowserRedirect: credentials.options?.skipBrowserRedirect, }) } /** * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. */ async exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse> { 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: Web3Credentials): Promise< | { data: { session: Session; user: User } error: null } | { data: { session: null; user: null }; error: AuthError } > { 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}"`) } } private async signInWithEthereum( credentials: EthereumWeb3Credentials ): Promise< | { data: { session: Session; user: User }; error: null } | { data: { session: null; user: null }; error: AuthError } > { // TODO: flatten type let message: string let signature: Hex if ('message' in credentials) { message = credentials.message signature = credentials.signature } else { const { chain, wallet, statement, options } = credentials let resolvedWallet: EthereumWallet if (!isBrowser()) { if (typeof wallet !== 'object' || !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 as any 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(options?.url ?? window.location.href) const accounts = await resolvedWallet .request({ method: 'eth_requestAccounts', }) .then((accs) => accs as string[]) .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 = options?.signInWithEthereum?.chainId if (!chainId) { const chainIdHex = await resolvedWallet.request({ method: 'eth_chainId', }) chainId = fromHex(chainIdHex as Hex) } const siweMessage: SiweMessage = { domain: url.host, address: address, statement: statement, uri: url.href, version: '1', chainId: chainId, nonce: options?.signInWithEthereum?.nonce, issuedAt: options?.signInWithEthereum?.issuedAt ?? new Date(), expirationTime: options?.signInWithEthereum?.expirationTime, notBefore: options?.signInWithEthereum?.notBefore, requestId: options?.signInWithEthereum?.requestId, resources: options?.signInWithEthereum?.resources, } message = createSiweMessage(siweMessage) // Sign message signature = (await resolvedWallet.request({ method: 'personal_sign', params: [toHex(message), address], })) as Hex } try { const { data, error } = await _request( this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { headers: this.headers, body: { chain: 'ethereum', message, signature, ...(credentials.options?.captchaToken ? { gotrue_meta_security: { captcha_token: credentials.options?.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: { ...data }, error } } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error } } throw error } } private async signInWithSolana(credentials: SolanaWeb3Credentials) { let message: string let signature: Uint8Array if ('message' in credentials) { message = credentials.message signature = credentials.signature } else { const { chain, wallet, statement, options } = credentials let resolvedWallet: SolanaWallet if (!isBrowser()) { if (typeof wallet !== 'object' || !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 as any 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(options?.url ?? window.location.href) if ('signIn' in resolvedWallet && resolvedWallet.signIn) { const output = await resolvedWallet.signIn({ issuedAt: new Date().toISOString(), ...options?.signInWithSolana, // non-overridable properties version: '1', domain: url.host, uri: url.href, ...(statement ? { statement } : null), }) let outputToProcess: any 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: ${options?.signInWithSolana?.issuedAt ?? new Date().toISOString()}`, ...(options?.signInWithSolana?.notBefore ? [`Not Before: ${options.signInWithSolana.notBefore}`] : []), ...(options?.signInWithSolana?.expirationTime ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : []), ...(options?.signInWithSolana?.chainId ? [`Chain ID: ${options.signInWithSolana.chainId}`] : []), ...(options?.signInWithSolana?.nonce ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), ...(options?.signInWithSolana?.requestId ? [`Request ID: ${options.signInWithSolana.requestId}`] : []), ...(options?.signInWithSolana?.resources?.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: { chain: 'solana', message, signature: bytesToBase64URL(signature), ...(credentials.options?.captchaToken ? { gotrue_meta_security: { captcha_token: credentials.options?.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: { ...data }, error } } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error } } throw error } } private async _exchangeCodeForSession(authCode: string): Promise< | { data: { session: Session; user: User; redirectType: string | null } error: null } | { data: { session: null; user: null; redirectType: null }; error: AuthError } > { const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`) const [codeVerifier, redirectType] = ((storageItem ?? '') as string).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: { ...data, redirectType: 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: SignInWithIdTokenCredentials): Promise<AuthTokenResponse> { 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?.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: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse> { try { if ('email' in credentials) { const { email, options } = credentials let codeChallenge: string | null = null let codeChallengeMethod: string | null = 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: options?.data ?? {}, create_user: options?.shouldCreateUser ?? true, gotrue_meta_security: { captcha_token: options?.captchaToken }, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod, }, redirectTo: 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: options?.data ?? {}, create_user: options?.shouldCreateUser ?? true, gotrue_meta_security: { captcha_token: options?.captchaToken }, channel: options?.channel ?? 'sms', }, }) return { data: { user: null, session: null, messageId: 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: VerifyOtpParams): Promise<AuthResponse> { try { let redirectTo: string | undefined = undefined let captchaToken: string | undefined = undefined if ('options' in params) { redirectTo = params.options?.redirectTo captchaToken = params.options?.captchaToken } const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { headers: this.headers, body: { ...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: Session | null = data.session const user: User = data.user if (session?.access_token) { await this._saveSession(session as 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: SignInWithSSO): Promise<SSOResponse> { try { let codeChallenge: string | null = null let codeChallengeMethod: string | null = null if (this.flowType === 'pkce') { ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( this.storage, this.storageKey ) } return await _request(this.fetch, 'POST', `${this.url}/sso`, { body: { ...('providerId' in params ? { provider_id: params.providerId } : null), ...('domain' in params ? { domain: params.domain } : null), redirect_to: params.options?.redirectTo ?? undefined, ...(params?.options?.captchaToken ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), skip_http_redirect: true, // fetch does not handle redirects 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(): Promise<AuthResponse> { await this.initializePromise return await this._acquireLock(-1, async () => { return await this._reauthenticate() }) } private async _reauthenticate(): Promise<AuthResponse> { 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: ResendParams): Promise<AuthOtpResponse> { 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?.captchaToken }, }, redirectTo: 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?.captchaToken }, }, }) return { data: { user: null, session: null, messageId: 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 const result = await this._acquireLock(-1, async () => { return this._useSession(async (result) => { return result }) }) return result } /** * Acquires a global lock based on the storage key. */ private async _acquireLock<R>(acquireTimeout: number, fn: () => Promise<R>): Promise<R> { this._debug('#_acquireLock', 'begin', acquireTimeout) try { if (this.lockAcquired) { const last = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve() const result = (async () => { await last return await fn() })() this.pendingInLock.push( (async () => { try { await result } catch (e: any) { // we just care if it finished } })() ) return result } return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey) try { this.lockAcquired = true const result = fn() this.pendingInLock.push( (async () => { try { await result } catch (e: any) { // we just care if it finished } })() ) await result // keep draining the queue until there's nothing to wait on while (this.pendingInLock.length) { const waitOn = [...this.pendingInLock] await Promise.all(waitOn) this.pendingInLock.splice(0, waitOn.length) } return await result } finally { this._debug('#_acquireLock', 'lock released for storage key', this.storageKey) this.lockAcquired = false } }) } finally { this._debug('#_acquireLock', 'end') } } /** * Use instead of {@link #getSession} inside the library. It is * semantically usually what you want, as getting a session involves some * processing afterwards that requires only one client operating on the * session at once across multiple tabs or processes. */ private async _useSession<R>( fn: ( result: | { data: { session: Session } error: null } | { data: { session: null } error: AuthError } | { data: { session: null } error: null } ) => Promise<R> ): Promise<R> { this._debug('#_useSession', 'begin') try { // the use of __loadSession here is the only correct use of the function! const result = await this.__loadSession() return await fn(result) } finally { this._debug('#_useSession', 'end') } } /** * NEVER USE DIRECTLY! * * Always use {@link #_useSession}. */ private async __loadSession(): Promise< | { data: { session: Session } error: null } | { data: { session: null } error: AuthError } | { data: { session: null } error: null } > { this._debug('#__loadSession()', 'begin') if (!this.lockAcquired) { this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack) } try { let currentSession: Session | null = null const maybeSession = await getItemAsync(this.storage, this.storageKey) this._debug('#getSession()', 'session from storage', maybeSession) if (maybeSession !== null) { if (this._isValidSession(maybeSession)) { currentSession = maybeSession } else { this._debug('#getSession()', 'session from storage is not valid') await this._removeSession() } } if (!currentSession) { return { data: { session: null }, error: null } } // A session is considered expired before the access token _actually_ // expires. When the autoRefreshToken option is off (or when the tab is // in the background), very eager users of getSession() -- like // realtime-js -- might send a valid JWT which will expire by the time it // reaches the server. const hasExpired = currentSession.expires_at ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS : false this._debug( '#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at ) if (!hasExpired) { if (this.userStorage) { const maybeUser: { user?: User | null } | null = (await getItemAsync( this.userStorage, this.storageKey + '-user' )) as any if (maybeUser?.user) { currentSession.user = maybeUser.user } else { currentSession.user = userNotAvailableProxy() } } if (this.storage.isServer && currentSession.user) { let suppressWarning = this.suppressGetSessionWarning const proxySession: Session = new Proxy(currentSession, {