UNPKG

@supabase/gotrue-js

Version:
1,200 lines 109 kB
import GoTrueAdminApi from './GoTrueAdminApi'; import { AuthError } from './lib/errors'; import { Fetch } from './lib/fetch'; import { Deferred } from './lib/helpers'; import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, AuthOAuthServerApi, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials, AuthPasskeyApi, ExperimentalFeatureFlags, SignInWithPasskeyCredentials, RegisterPasskeyCredentials, AuthPasskeyRegistrationVerifyResponse, AuthPasskeyAuthenticationVerifyResponse } from './lib/types'; export default class GoTrueClient { private static nextInstanceID; private instanceID; /** * 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; /** * Namespace for the OAuth 2.1 authorization server methods. * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. * Used to implement the authorization code flow on the consent page. */ oauth: AuthOAuthServerApi; /** * Namespace for passkey methods. * Includes lower-level two-step registration/authentication and passkey management. * * Requires `auth.experimental.passkey: true`; otherwise all methods throw. */ passkey: AuthPasskeyApi; /** * 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(): { keys: JWK[]; }; protected set jwks(value: { keys: JWK[]; }); protected get jwks_cached_at(): number; protected set jwks_cached_at(value: number); protected autoRefreshToken: boolean; protected persistSession: boolean; protected storage: SupportedStorage; /** * @experimental */ protected userStorage: SupportedStorage | null; protected memoryStorage: { [key: string]: string; } | null; protected stateChangeEmitters: Map<string | symbol, Subscription>; protected autoRefreshTicker: ReturnType<typeof setInterval> | null; protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | null; protected visibilityChangedCallback: (() => Promise<any>) | null; protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null; /** * Cache of the most recent refresh failure, keyed by the refresh token * that failed. Serial callers passing the *same* token within * `REFRESH_FAILURE_COOLDOWN_MS` (including subsequent auto-refresh ticks) * receive this cached result instead of firing another `/token` request. * Callers passing a *different* token (token rotation pickup, explicit * `setSession`/`refreshSession({ refresh_token })`, multi-account switch) * bypass the cache and attempt a fresh refresh as they should. * Cleared on any successful refresh (locally or via BroadcastChannel from * another tab) and on `_removeSession`. * * Pairs with `refreshingDeferred`: concurrent callers share the in-flight * promise, serial callers within the cooldown share the failure result. */ protected lastRefreshFailure: { refreshToken: string; result: CallRefreshTokenResult; expiresAt: number; } | null; /** * Monotonic counter incremented at the top of `_removeSession`, before any * `await`. The commit guard inside `_callRefreshToken` captures this value * before `_saveSession` and re-checks it after, so a `signOut` that * interleaves inside `_saveSession`'s storage-write awaits is still caught * (the post-fetch storage snapshot alone misses that window). */ protected _sessionRemovalEpoch: number; /** * 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; /** * Non-null only while `initialize()` is running. While open, * `_notifyAllSubscribers` enqueues init-chain notifications (those fired with * `broadcast = true`, i.e. from `_recoverAndRefresh`) into this array instead * of firing directly, so that `initializePromise` is guaranteed to be * resolved before any subscriber callback runs. Callbacks that call * `getSession()` / `getUser()` etc. would otherwise deadlock because those * methods await `initializePromise`. Notifications from the incoming * BroadcastChannel handler (`broadcast = false`) are not enqueued — they fire * immediately. Flushed (in order) by `initialize()` after `initializePromise` * settles. */ private _pendingInitNotifications; protected detectSessionInUrl: boolean | ((url: URL, params: { [parameter: string]: string; }) => boolean); protected url: string; protected headers: { [key: string]: string; }; protected hasCustomAuthorizationHeader: boolean; protected suppressGetSessionWarning: boolean; protected fetch: Fetch; /** * Custom lock function passed via `settings.lock`. When non-null, every auth * operation runs inside `_acquireLock`. When null (the default), the client * uses its lockless coordination (refresh single-flight + commit guard). * TODO(v3): remove along with the legacy lock path. */ protected lock: LockFunc | null; protected lockAcquired: boolean; protected pendingInLock: Promise<any>[]; protected throwOnError: boolean; /** * Only consulted when a custom `lock` is supplied. TODO(v3): remove. */ protected lockAcquireTimeout: number; /** * Opt-in flags for experimental features. Defaults to an empty object. * See `GoTrueClientOptions.experimental`. */ protected experimental: ExperimentalFeatureFlags; /** * Used to broadcast state change events to other tabs listening. */ protected broadcastChannel: BroadcastChannel | null; protected logDebugMessages: boolean; protected logger: (message: string, ...args: any[]) => void; /** * Create a new client for use in the browser. * * @example Using supabase-js (recommended) * ```ts * import { createClient } from '@supabase/supabase-js' * * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') * const { data, error } = await supabase.auth.getUser() * ``` * * @example Standalone import for bundle-sensitive environments * ```ts * import { GoTrueClient } from '@supabase/auth-js' * * const auth = new GoTrueClient({ * url: 'https://xyzcompany.supabase.co/auth/v1', * headers: { apikey: 'your-publishable-key' }, * storageKey: 'supabase-auth', * }) * ``` */ constructor(options: GoTrueClientOptions); /** * Returns whether error throwing mode is enabled for this client. */ isThrowOnErrorEnabled(): boolean; /** * Centralizes return handling with optional error throwing. When `throwOnError` is enabled * and the provided result contains a non-nullish error, the error is thrown instead of * being returned. This ensures consistent behavior across all public API methods. */ private _returnResult; private _logPrefix; private _debug; /** * Initialize the auth client by loading the session from storage or * detecting it from the URL after an OAuth, magic-link, or password-recovery * redirect. * * **Most callers do not need to invoke this directly.** The client calls it * automatically during construction, and to react to sign-in events (including * post-redirect events) you should subscribe to `onAuthStateChange` rather * than awaiting `initialize()`. * * You only need to call it manually when you have opted out of the automatic * call by passing `skipAutoInitialize: true` — for example, in an SSR context * where you need to control initialization timing. In that case, awaiting * `initialize()` returns the resolved session result (or any error encountered * while detecting it from the URL). * * @category Auth */ initialize(): Promise<InitializeResult>; /** * 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 _initialize; /** * Creates a new anonymous user. * * @returns A session where the is_anonymous claim in the access token JWT set to true * * @category Auth * * @remarks * - Returns an anonymous user * - It is recommended to set up captcha for anonymous sign-ins to prevent abuse. You can pass in the captcha token in the `options` param. * * @example Create an anonymous user * ```js * const { data, error } = await supabase.auth.signInAnonymously({ * options: { * captchaToken * } * }); * ``` * * @exampleResponse Create an anonymous user * ```json * { * "data": { * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": {}, * "user_metadata": {}, * "identities": [], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "is_anonymous": true * }, * "session": { * "access_token": "<ACCESS_TOKEN>", * "token_type": "bearer", * "expires_in": 3600, * "expires_at": 1700000000, * "refresh_token": "<REFRESH_TOKEN>", * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": {}, * "user_metadata": {}, * "identities": [], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "is_anonymous": true * } * } * }, * "error": null * } * ``` * * @example Create an anonymous user with custom user metadata * ```js * const { data, error } = await supabase.auth.signInAnonymously({ * options: { * data * } * }) * ``` */ signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>; /** * 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 * * @category Auth * * @remarks * - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers). * - **Confirm email** determines if users need to confirm their email address after signing up. * - If **Confirm email** is enabled, a `user` is returned but `session` is null. * - If **Confirm email** is disabled, both a `user` and a `session` are returned. * - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration). * - If signUp() is called for an existing confirmed user: * - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned. * - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned. * - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser). * * @example Sign up with an email and password * ```js * const { data, error } = await supabase.auth.signUp({ * email: 'example@email.com', * password: 'example-password', * }) * ``` * * @exampleResponse Sign up with an email and password * ```json * // Some fields may be null if "confirm email" is enabled. * { * "data": { * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.com", * "email_confirmed_at": "2024-01-01T00:00:00Z", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * "provider": "email", * "providers": [ * "email" * ] * }, * "user_metadata": {}, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z" * }, * "session": { * "access_token": "<ACCESS_TOKEN>", * "token_type": "bearer", * "expires_in": 3600, * "expires_at": 1700000000, * "refresh_token": "<REFRESH_TOKEN>", * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.com", * "email_confirmed_at": "2024-01-01T00:00:00Z", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * "provider": "email", * "providers": [ * "email" * ] * }, * "user_metadata": {}, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z" * } * } * }, * "error": null * } * ``` * * @example Sign up with a phone number and password (SMS) * ```js * const { data, error } = await supabase.auth.signUp({ * phone: '123456789', * password: 'example-password', * options: { * channel: 'sms' * } * }) * ``` * * @exampleDescription Sign up with a phone number and password (whatsapp) * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature. * * @example Sign up with a phone number and password (whatsapp) * ```js * const { data, error } = await supabase.auth.signUp({ * phone: '123456789', * password: 'example-password', * options: { * channel: 'whatsapp' * } * }) * ``` * * @example Sign up with additional user metadata * ```js * const { data, error } = await supabase.auth.signUp( * { * email: 'example@email.com', * password: 'example-password', * options: { * data: { * first_name: 'John', * age: 27, * } * } * } * ) * ``` * * @exampleDescription Sign up with a redirect URL * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. * * @example Sign up with a redirect URL * ```js * const { data, error } = await supabase.auth.signUp( * { * email: 'example@email.com', * password: 'example-password', * options: { * emailRedirectTo: 'https://example.com/welcome' * } * } * ) * ``` */ signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>; /** * 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. * * @category Auth * * @remarks * - Requires either an email and password or a phone number and password. * * @example Sign in with email and password * ```js * const { data, error } = await supabase.auth.signInWithPassword({ * email: 'example@email.com', * password: 'example-password', * }) * ``` * * @exampleResponse Sign in with email and password * ```json * { * "data": { * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.com", * "email_confirmed_at": "2024-01-01T00:00:00Z", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * "provider": "email", * "providers": [ * "email" * ] * }, * "user_metadata": {}, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z" * }, * "session": { * "access_token": "<ACCESS_TOKEN>", * "token_type": "bearer", * "expires_in": 3600, * "expires_at": 1700000000, * "refresh_token": "<REFRESH_TOKEN>", * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.com", * "email_confirmed_at": "2024-01-01T00:00:00Z", * "phone": "", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * "provider": "email", * "providers": [ * "email" * ] * }, * "user_metadata": {}, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z" * } * } * }, * "error": null * } * ``` * * @example Sign in with phone and password * ```js * const { data, error } = await supabase.auth.signInWithPassword({ * phone: '+13334445555', * password: 'some-password', * }) * ``` * * @exampleDescription Handling errors * Log the full `error` object so fields like `code`, `status`, and `name` aren't hidden. The `error.code` (e.g. `'invalid_credentials'`, `'email_not_confirmed'`) is often more useful for branching than `error.message`, and the full object surfaces both. * * @example Handling errors * ```js * const { data, error } = await supabase.auth.signInWithPassword({ * email: 'example@email.com', * password: 'example-password', * }) * if (error) { * console.error(error) * return * } * ``` */ signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>; /** * Log in an existing user via a third-party provider. * This method supports the PKCE flow. * * @category Auth * * @remarks * - This method is used for signing in using [Social Login (OAuth) providers](/docs/guides/auth#configure-third-party-providers). * - It works by redirecting your application to the provider's authorization screen, before bringing back the user to your app. * * @example Sign in using a third-party provider * ```js * const { data, error } = await supabase.auth.signInWithOAuth({ * provider: 'github' * }) * ``` * * @exampleResponse Sign in using a third-party provider * ```json * { * data: { * provider: 'github', * url: <PROVIDER_URL_TO_REDIRECT_TO>, * flowId: <PKCE_FLOW_ID_OR_NULL> * }, * error: null * } * ``` * * @exampleDescription Sign in using a third-party provider with redirect * - When the OAuth provider successfully authenticates the user, they are redirected to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). It does not redirect the user immediately after invoking this method. * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. * * @example Sign in using a third-party provider with redirect * ```js * const { data, error } = await supabase.auth.signInWithOAuth({ * provider: 'github', * options: { * redirectTo: 'https://example.com/welcome' * } * }) * ``` * * @exampleDescription Sign in with scopes and access provider tokens * If you need additional access from an OAuth provider, in order to access provider specific APIs in the name of the user, you can do this by passing in the scopes the user should authorize for your application. Note that the `scopes` option takes in **a space-separated list** of scopes. * * Because OAuth sign-in often includes redirects, you should register an `onAuthStateChange` callback immediately after you create the Supabase client. This callback will listen for the presence of `provider_token` and `provider_refresh_token` properties on the `session` object and store them in local storage. The client library will emit these values **only once** immediately after the user signs in. You can then access them by looking them up in local storage, or send them to your backend servers for further processing. * * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend. * * @example Sign in with scopes and access provider tokens * ```js * // Register this immediately after calling createClient! * // Because signInWithOAuth causes a redirect, you need to fetch the * // provider tokens from the callback. * supabase.auth.onAuthStateChange((event, session) => { * if (session && session.provider_token) { * window.localStorage.setItem('oauth_provider_token', session.provider_token) * } * * if (session && session.provider_refresh_token) { * window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token) * } * * if (event === 'SIGNED_OUT') { * window.localStorage.removeItem('oauth_provider_token') * window.localStorage.removeItem('oauth_provider_refresh_token') * } * }) * * // Call this on your Sign in with GitHub button to initiate OAuth * // with GitHub with the requested elevated scopes. * await supabase.auth.signInWithOAuth({ * provider: 'github', * options: { * scopes: 'repo gist notifications' * } * }) * ``` */ signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>; /** * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. * * @category Auth * * @remarks * - Used when `flowType` is set to `pkce` in client options. * - When several PKCE flows are in flight at once, pass `options.flowId` so * the code is exchanged with the verifier created by that specific flow. * The flow id is returned by `signInWithOAuth`, and with * `experimental.appendPkceFlowIdToRedirects` enabled it also arrives on * your callback URL as the reserved `sb_flow_id` query parameter (read * automatically in a browser). * - When a flow id is present but its stored verifier is gone (evicted, * already used, or from another device), the call fails with a verifier * missing error instead of trying another flow's verifier — a mismatched * verifier would consume the single-use code. Without any flow id the * most recently stored verifier is used, as before. * * @example Exchange Auth Code * ```js * supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225') * ``` * * @example Exchange Auth Code for a specific flow (e.g. in a server-side callback handler) * ```js * const flowId = requestUrl.searchParams.get('sb_flow_id') * supabase.auth.exchangeCodeForSession(code, flowId ? { flowId } : undefined) * ``` * * @exampleResponse Exchange Auth Code * ```json * { * "data": { * session: { * access_token: '<ACCESS_TOKEN>', * token_type: 'bearer', * expires_in: 3600, * expires_at: 1700000000, * refresh_token: '<REFRESH_TOKEN>', * user: { * id: '11111111-1111-1111-1111-111111111111', * aud: 'authenticated', * role: 'authenticated', * email: 'example@email.com' * email_confirmed_at: '2024-01-01T00:00:00Z', * phone: '', * confirmation_sent_at: '2024-01-01T00:00:00Z', * confirmed_at: '2024-01-01T00:00:00Z', * last_sign_in_at: '2024-01-01T00:00:00Z', * app_metadata: { * "provider": "email", * "providers": [ * "email", * "<OTHER_PROVIDER>" * ] * }, * user_metadata: { * email: 'email@email.com', * email_verified: true, * full_name: 'User Name', * iss: '<ISS>', * name: 'User Name', * phone_verified: false, * provider_id: '<PROVIDER_ID>', * sub: '<SUB>' * }, * identities: [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "email@example.com" * }, * { * "identity_id": "33333333-3333-3333-3333-333333333333", * "id": "<ID>", * "user_id": "<USER_ID>", * "identity_data": { * "email": "example@email.com", * "email_verified": true, * "full_name": "User Name", * "iss": "<ISS>", * "name": "User Name", * "phone_verified": false, * "provider_id": "<PROVIDER_ID>", * "sub": "<SUB>" * }, * "provider": "<PROVIDER>", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * created_at: '2024-01-01T00:00:00Z', * updated_at: '2024-01-01T00:00:00Z', * is_anonymous: false * }, * provider_token: '<PROVIDER_TOKEN>', * provider_refresh_token: '<PROVIDER_REFRESH_TOKEN>' * }, * user: { * id: '11111111-1111-1111-1111-111111111111', * aud: 'authenticated', * role: 'authenticated', * email: 'example@email.com', * email_confirmed_at: '2024-01-01T00:00:00Z', * phone: '', * confirmation_sent_at: '2024-01-01T00:00:00Z', * confirmed_at: '2024-01-01T00:00:00Z', * last_sign_in_at: '2024-01-01T00:00:00Z', * app_metadata: { * provider: 'email', * providers: [ * "email", * "<OTHER_PROVIDER>" * ] * }, * user_metadata: { * email: 'email@email.com', * email_verified: true, * full_name: 'User Name', * iss: '<ISS>', * name: 'User Name', * phone_verified: false, * provider_id: '<PROVIDER_ID>', * sub: '<SUB>' * }, * identities: [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "email@example.com" * }, * { * "identity_id": "33333333-3333-3333-3333-333333333333", * "id": "<ID>", * "user_id": "<USER_ID>", * "identity_data": { * "email": "example@email.com", * "email_verified": true, * "full_name": "User Name", * "iss": "<ISS>", * "name": "User Name", * "phone_verified": false, * "provider_id": "<PROVIDER_ID>", * "sub": "<SUB>" * }, * "provider": "<PROVIDER>", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * created_at: '2024-01-01T00:00:00Z', * updated_at: '2024-01-01T00:00:00Z', * is_anonymous: false * }, * redirectType: null * }, * "error": null * } * ``` */ exchangeCodeForSession(authCode: string, options?: { flowId?: string; }): Promise<AuthTokenResponse>; /** * 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 * * @category Auth * * @remarks * - Uses a Web3 (Ethereum, Solana) wallet to sign a user in. * - Read up on the [potential for abuse](/docs/guides/auth/auth-web3#potential-for-abuse) before using it. * * @example Sign in with Solana or Ethereum (Window API) * ```js * // uses window.ethereum for the wallet * const { data, error } = await supabase.auth.signInWithWeb3({ * chain: 'ethereum', * statement: 'I accept the Terms of Service at https://example.com/tos' * }) * * // uses window.solana for the wallet * const { data, error } = await supabase.auth.signInWithWeb3({ * chain: 'solana', * statement: 'I accept the Terms of Service at https://example.com/tos' * }) * ``` * * @example Sign in with Ethereum (Message and Signature) * ```js * const { data, error } = await supabase.auth.signInWithWeb3({ * chain: 'ethereum', * message: '<sign in with ethereum message>', * signature: '<hex of the ethereum signature over the message>', * }) * ``` * * @example Sign in with Solana (Brave) * ```js * const { data, error } = await supabase.auth.signInWithWeb3({ * chain: 'solana', * statement: 'I accept the Terms of Service at https://example.com/tos', * wallet: window.braveSolana * }) * ``` * * @example Sign in with Solana (Wallet Adapter) * ```jsx * function SignInButton() { * const wallet = useWallet() * * return ( * <> * {wallet.connected ? ( * <button * onClick={() => { * supabase.auth.signInWithWeb3({ * chain: 'solana', * statement: 'I accept the Terms of Service at https://example.com/tos', * wallet, * }) * }} * > * Sign in with Solana * </button> * ) : ( * <WalletMultiButton /> * )} * </> * ) * } * * function App() { * const endpoint = clusterApiUrl('devnet') * const wallets = useMemo(() => [], []) * * return ( * <ConnectionProvider endpoint={endpoint}> * <WalletProvider wallets={wallets}> * <WalletModalProvider> * <SignInButton /> * </WalletModalProvider> * </WalletProvider> * </ConnectionProvider> * ) * } * ``` */ signInWithWeb3(credentials: Web3Credentials): Promise<{ data: { session: Session; user: User; }; error: null; } | { data: { session: null; user: null; }; error: AuthError; }>; private signInWithEthereum; private signInWithSolana; private _exchangeCodeForSession; /** * Allows signing in with an OIDC ID token. The authentication provider used * should be enabled and configured. * * @category Auth * * @remarks * - Use an ID token to sign in. * - Especially useful when implementing sign in using native platform dialogs in mobile or desktop apps using Sign in with Apple or Sign in with Google on iOS and Android. * - You can also use Google's [One Tap](https://developers.google.com/identity/gsi/web/guides/display-google-one-tap) and [Automatic sign-in](https://developers.google.com/identity/gsi/web/guides/automatic-sign-in-sign-out) via this API. * * @example Sign In using ID Token * ```js * const { data, error } = await supabase.auth.signInWithIdToken({ * provider: 'google', * token: 'your-id-token' * }) * ``` * * @exampleResponse Sign In using ID Token * ```json * { * "data": { * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * ... * }, * "user_metadata": { * ... * }, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "provider": "google", * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * }, * "session": { * "access_token": "<ACCESS_TOKEN>", * "token_type": "bearer", * "expires_in": 3600, * "expires_at": 1700000000, * "refresh_token": "<REFRESH_TOKEN>", * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * ... * }, * "user_metadata": { * ... * }, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "provider": "google", * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * } * } * }, * "error": null * } * ``` */ signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>; /** * 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. * * @category Auth * * @remarks * - Requires either an email or phone number. * - This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number. * - If the user doesn't exist, `signInWithOtp()` will signup the user instead. To restrict this behavior, you can set `shouldCreateUser` in `SignInWithPasswordlessCredentials.options` to `false`. * - If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP. * - If you're using phone, you can configure whether you want the user to receive a OTP. * - The magic link's destination URL is determined by the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. * - Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, [modify the magic link email template](/dashboard/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`. * - See our [Twilio Phone Auth Guide](/docs/guides/auth/phone-login?showSMSProvider=Twilio) for details about configuring WhatsApp sign in. * * @exampleDescription Sign in with email * The user will be sent an email which contains either a magiclink or a OTP or both. By default, a given user can only request a OTP once every 60 seconds. * * @example Sign in with email * ```js * const { data, error } = await supabase.auth.signInWithOtp({ * email: 'example@email.com', * options: { * emailRedirectTo: 'https://example.com/welcome' * } * }) * ``` * * @exampleResponse Sign in with email * ```json * { * "data": { * "user": null, * "session": null * }, * "error": null * } * ``` * * @exampleDescription Sign in with SMS OTP * The user will be sent a SMS which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. * * @example Sign in with SMS OTP * ```js * const { data, error } = await supabase.auth.signInWithOtp({ * phone: '+13334445555', * }) * ``` * * @exampleDescription Sign in with WhatsApp OTP * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature. * * @example Sign in with WhatsApp OTP * ```js * const { data, error } = await supabase.auth.signInWithOtp({ * phone: '+13334445555', * options: { * channel:'whatsapp', * } * }) * ``` */ signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>; /** * Log in a user given a User supplied OTP or TokenHash received through mobile or email. * * @category Auth * * @remarks * - The `verifyOtp` method takes in different verification types. * - If a phone number is used, the type can either be: * 1. `sms` – Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in. * 2. `phone_change` – Used when verifying an OTP sent to a new phone number during a phone number update process. * - If an email address is used, the type can be one of the following (note: `signup` and `magiclink` types are deprecated): * 1. `email` – Used when verifying an OTP sent to the user's email during sign-up or sign-in. * 2. `recovery` – Used when verifying an OTP sent for account recovery, typically after a password reset request. * 3. `invite` – Used when verifying an OTP sent as part of an invitation to join a project or organization. * 4. `email_change` – Used when verifying an OTP sent to a new email address during an email update process. * - The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user. * - The `TokenHash` is contained in the [email templates](/docs/guides/auth/auth-email-templates) and can be used to sign in. You may wish to use the hash for the PKCE flow for Server Side Auth. Read [the Password-based Auth guide](/docs/guides/auth/passwords) for more details. * * @example Verify Signup One-Time Password (OTP) * ```js * const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'}) * ``` * * @exampleResponse Verify Signup One-Time Password (OTP) * ```json * { * "data": { * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.com", * "email_confirmed_at": "2024-01-01T00:00:00Z", * "phone": "", * "confirmed_at": "2024-01-01T00:00:00Z", * "recovery_sent_at": "2024-01-01T00:00:00Z", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "app_metadata": { * "provider": "email", * "providers": [ * "email" * ] * }, * "user_metadata": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "identities": [ * { * "identity_id": "22222222-2222-2222-2222-222222222222", * "id": "11111111-1111-1111-1111-111111111111", * "user_id": "11111111-1111-1111-1111-111111111111", * "identity_data": { * "email": "example@email.com", * "email_verified": false, * "phone_verified": false, * "sub": "11111111-1111-1111-1111-111111111111" * }, * "provider": "email", * "last_sign_in_at": "2024-01-01T00:00:00Z", * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "email": "example@email.com" * } * ], * "created_at": "2024-01-01T00:00:00Z", * "updated_at": "2024-01-01T00:00:00Z", * "is_anonymous": false * }, * "session": { * "access_token": "<ACCESS_TOKEN>", * "token_type": "bearer", * "expires_in": 3600, * "expires_at": 1700000000, * "refresh_token": "<REFRESH_TOKEN>", * "user": { * "id": "11111111-1111-1111-1111-111111111111", * "aud": "authenticated", * "role": "authenticated", * "email": "example@email.co