UNPKG

@skorpland/auth-js

Version:

Official client library for Powerbase Auth

1,080 lines (1,079 loc) 93.7 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 { Deferred, getItemAsync, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, supportsLocalStorage, parseParametersFromURL, getCodeChallengeAndMethod, getAlgorithm, validateExp, decodeJWT, } from './lib/helpers'; import { localStorageAdapter, memoryLocalStorageAdapter } from './lib/local-storage'; import { polyfillGlobalThis } from './lib/polyfills'; import { version } from './lib/version'; import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'; import { stringToUint8Array } from './lib/base64url'; 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(); } export default class GoTrueClient { /** * Create a new client for use in the browser. */ constructor(options) { var _a, _b; 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 the auth state is known and it's save 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; } 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 = localStorageAdapter; } else { this.memoryStorage = {}; this.storage = memoryLocalStorageAdapter(this.memoryStorage); } } } 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(); } _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); }); } 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; 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. */ async _acquireLock(acquireTimeout, fn) { 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) { // 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) { // 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. */ async _useSession(fn) { 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}. */ async __loadSession() { this._debug('#__loadSession()', 'begin'); if (!this.lockAcquired) { this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); } try { let currentSession = 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.storage.isServer) { let suppressWarning = this.suppressGetSessionWarning; const proxySession = new Proxy(currentSession, { get: (target, prop, receiver) => { if (!suppressWarning && prop === 'user') { // only show warning when the user object is being accessed from the server console.warn('Using the user object as returned from powerbase.auth.getSession() or from some powerbase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use powerbase.auth.getUser() instead which authenticates the data by contacting the Powerbase Auth server.'); suppressWarning = true; // keeps this proxy instance from logging additional warnings this.suppressGetSessionWarning = true; // keeps this client's future proxy instances from warning } return Reflect.get(target, prop, receiver); }, }); currentSession = proxySession; } return { data: { session: currentSession }, error: null }; } const { session, error } = await this._callRefreshToken(currentSession.refresh_token); if (error) { return { data: { session: null }, error }; } return { data: { session }, error: null }; } finally { this._debug('#__loadSession()', 'end'); } } /** * Gets the current user details if there is an existing session. This method * performs a network request to the Powerbase Auth server, so the returned * value is authentic and can be used to base authorization rules on. * * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. */ async getUser(jwt) { if (jwt) { return await this._getUser(jwt); } await this.initializePromise; const result = await this._acquireLock(-1, async () => { return await this._getUser(); }); return result; } async _getUser(jwt) { try { if (jwt) { return await _request(this.fetch, 'GET', `${this.url}/user`, { headers: this.headers, jwt: jwt, xform: _userResponse, }); } return await this._useSession(async (result) => { var _a, _b, _c; const { data, error } = result; if (error) { throw error; } // returns an error if there is no access_token or custom authorization header if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { return { data: { user: null }, error: new AuthSessionMissingError() }; } return await _request(this.fetch, 'GET', `${this.url}/user`, { headers: this.headers, jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, xform: _userResponse, }); }); } catch (error) { if (isAuthError(error)) { if (isAuthSessionMissingError(error)) { // JWT contains a `session_id` which does not correspond to an active // session in the database, indicating the user is signed out. await this._removeSession(); await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); } return { data: { user: null }, error }; } throw error; } } /** * Updates user data for a logged in user. */ async updateUser(attributes, options = {}) { await this.initializePromise; return await this._acquireLock(-1, async () => { return await this._updateUser(attributes, options); }); } async _updateUser(attributes, options = {}) { try { return await this._useSession(async (result) => { const { data: sessionData, error: sessionError } = result; if (sessionError) { throw sessionError; } if (!sessionData.session) { throw new AuthSessionMissingError(); } const session = sessionData.session; let codeChallenge = null; let codeChallengeMethod = null; if (this.flowType === 'pkce' && attributes.email != null) { ; [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); } const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { headers: this.headers, redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), jwt: session.access_token, xform: _userResponse, }); if (userError) throw userError; session.user = data.user; await this._saveSession(session); await this._notifyAllSubscribers('USER_UPDATED', session); return { data: { user: session.user }, error: null }; }); } catch (error) { if (isAuthError(error)) { return { data: { user: null }, error }; } throw error; } } /** * 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. * If the refresh token or access token in the current session is invalid, an error will be thrown. * @param currentSession The current session that minimally contains an access token and refresh token. */ async setSession(currentSession) { await this.initializePromise; return await this._acquireLock(-1, async () => { return await this._setSession(currentSession); }); } async _setSession(currentSession) { try { if (!currentSession.access_token || !currentSession.refresh_token) { throw new AuthSessionMissingError(); } const timeNow = Date.now() / 1000; let expiresAt = timeNow; let hasExpired = true; let session = null; const { payload } = decodeJWT(currentSession.access_token); if (payload.exp) { expiresAt = payload.exp; hasExpired = expiresAt <= timeNow; } if (hasExpired) { const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); if (error) { return { data: { user: null, session: null }, error: error }; } if (!refreshedSession) { return { data: { user: null, session: null }, error: null }; } session = refreshedSession; } else { const { data, error } = await this._getUser(currentSession.access_token); if (error) { throw error; } session = { access_token: currentSession.access_token, refresh_token: currentSession.refresh_token, user: data.user, token_type: 'bearer', expires_in: expiresAt - timeNow, expires_at: expiresAt, }; await this._saveSession(session); await this._notifyAllSubscribers('SIGNED_IN', session); } return { data: { user: session.user, session }, error: null }; } catch (error) { if (isAuthError(error)) { return { data: { session: null, user: null }, error }; } throw error; } } /** * Returns a new session, regardless of expiry status. * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). * If the current session's refresh token is invalid, an error will be thrown. * @param currentSession The current session. If passed in, it must contain a refresh token. */ async refreshSession(currentSession) { await this.initializePromise; return await this._acquireLock(-1, async () => { return await this._refreshSession(currentSession); }); } async _refreshSession(currentSession) { try { return await this._useSession(async (result) => { var _a; if (!currentSession) { const { data, error } = result; if (error) { throw error; } currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; } if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { throw new AuthSessionMissingError(); } const { session, error } = await this._callRefreshToken(currentSession.refresh_token); if (error) { return { data: { user: null, session: null }, error: error }; } if (!session) { return { data: { user: null, session: null }, error: null }; } return { data: { user: session.user, session }, error: null }; }); } catch (error) { if (isAuthError(error)) { return { data: { user: null, session: null }, error }; } throw error; } } /** * Gets the session data from a URL string */ async _getSessionFromURL(params, callbackUrlType) { try { if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.'); // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. if (params.error || params.error_description || params.error_code) { // The error class returned implies that the redirect is from an implicit grant flow // but it could also be from a redirect error from a PKCE flow. throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { error: params.error || 'unspecified_error', code: params.error_code || 'unspecified_code',