import { createContext } from 'react'; import type { Credentials, User, WebAuthorizeParameters, ClearSessionParameters, PasswordRealmParameters, ExchangeParameters, CreateUserParameters, PasswordlessEmailParameters, LoginEmailParameters, PasswordlessSmsParameters, LoginSmsParameters, MfaChallengeParameters, LoginOobParameters, LoginOtpParameters, LoginRecoveryCodeParameters, ExchangeNativeSocialParameters, CustomTokenExchangeParameters, SSOExchangeParameters, RevokeOptions, ResetPasswordParameters, MfaChallengeResponse, DPoPHeadersParams, SessionTransferCredentials, } from '../types'; import type { ApiCredentials } from '../core/models'; import type { NativeAuthorizeOptions, NativeClearSessionOptions, } from '../types/platform-specific'; import type { AuthState } from './reducer'; /** * The contract for the value provided by the Auth0Context. * This is the interface that developers will interact with when using the `useAuth0` hook. */ export interface Auth0ContextInterface extends AuthState { /** * Initiates the web-based authentication flow. * @param parameters The parameters to send to the `/authorize` endpoint. * @param options Platform-specific options to customize the authentication experience. * @returns A promise that resolves with the user's credentials upon successful authentication. * @throws {AuthError} If the authentication fails. */ authorize: ( parameters?: WebAuthorizeParameters, options?: NativeAuthorizeOptions ) => Promise; /** * Clears the user's session and logs them out. * @param parameters The parameters to send to the `/v2/logout` endpoint. * @param options Platform-specific options to customize the logout experience. * @returns A promise that resolves when the session has been cleared. * @throws {AuthError} If the logout fails. */ clearSession: ( parameters?: ClearSessionParameters, options?: NativeClearSessionOptions ) => Promise; /** * Saves the user's credentials. * @param credentials The credentials to save. * @returns A promise that resolves when the credentials have been saved. * @throws {AuthError} If the save fails. */ saveCredentials: (credentials: Credentials) => Promise; /** * Retrieves the stored credentials, refreshing them if necessary. * @param scope The scopes to request for the new access token (used during refresh). * @param minTtl The minimum time-to-live (in seconds) required for the access token. * @param parameters Additional parameters to send during the refresh request. * @param forceRefresh If true, forces a refresh of the credentials. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If credentials cannot be retrieved or refreshed. */ getCredentials: ( scope?: string, minTtl?: number, parameters?: Record, forceRefresh?: boolean ) => Promise; /** * Clears the user's credentials without clearing their web session and logs them out. * * @remarks * **Platform specific:** This method is only available in the context of a Android/iOS application. * @returns A promise that resolves when the credentials have been cleared. */ clearCredentials: () => Promise; /** * Checks if a valid, non-expired set of credentials exists in storage. * This is a quick, local check and does not perform a network request. * * @param minTtl The minimum time-to-live (in seconds) required for the access token to be considered valid. Defaults to 0. * @returns A promise that resolves with `true` if valid credentials exist, `false` otherwise. */ hasValidCredentials: (minTtl?: number) => Promise; /** * Retrieves API-specific credentials. * * @param audience The identifier of the API for which to get credentials. * @param scope The scopes to request for the new access token. * @param minTtl The minimum time-to-live (in seconds) required for the access token. If the token expires sooner, a refresh will be attempted. * @param parameters Additional parameters to send during the token refresh request. * @returns A promise that resolves with the API credentials. * @throws {AuthError} If credentials cannot be retrieved or refreshed. */ getApiCredentials( audience: string, scope?: string, minTtl?: number, parameters?: Record ): Promise; /** * Removes cached credentials for a specific audience. * * @param audience The identifier of the API for which to clear credentials. * @returns A promise that resolves when the credentials are cleared. */ clearApiCredentials(audience: string): Promise; /** * Cancels the ongoing web authentication process. * This works only on iOS. On other platforms, it will resolve without performing an action. */ cancelWebAuth: () => Promise; /** * Authenticates a user with their username and password. * @remarks This method is not supported on the web platform. * @param parameters The parameters for the password-realm grant. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authentication fails. */ loginWithPasswordRealm: ( parameters: PasswordRealmParameters ) => Promise; /** * Creates a new user in a database connection. * @param parameters The parameters for creating the new user. * @returns A promise that resolves with the new user's profile information. * @throws {AuthError} If the user creation fails. */ createUser: (parameters: CreateUserParameters) => Promise>; /** * Resets the user's password. * @param parameters The parameters for resetting the password. * @returns A promise that resolves when the password has been reset. * @throws {AuthError} If the reset fails. */ resetPassword: (parameters: ResetPasswordParameters) => Promise; /** * Exchanges an authorization code for tokens. * This is useful in advanced scenarios where you manage the code flow manually. * @param parameters The parameters containing the authorization code and verifier. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the exchange fails. */ authorizeWithExchange: ( parameters: ExchangeParameters ) => Promise; /** * Exchanges an authorization code for native social tokens. * @param parameters The parameters containing the authorization code and verifier. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the exchange fails. */ authorizeWithExchangeNativeSocial: ( parameters: ExchangeNativeSocialParameters ) => Promise; /** * Exchanges an external identity provider token for Auth0 tokens. * Uses RFC 8693 OAuth 2.0 Token Exchange specification. * * @param parameters The token exchange parameters. * @returns A promise that resolves with the user's Auth0 credentials. * @throws {AuthError} If the token exchange fails. * * @example * ```typescript * const credentials = await customTokenExchange({ * subjectToken: 'external-provider-token', * subjectTokenType: 'urn:acme:legacy-system-token', * scope: 'openid profile email', * audience: 'https://api.example.com', * organization: 'org_123' * }); * ``` */ customTokenExchange: ( parameters: CustomTokenExchangeParameters ) => Promise; /** * Sends a verification code to the user's email. * @param parameters The parameters for sending the email code. * @throws {AuthError} If sending the email code fails. */ sendEmailCode: (parameters: PasswordlessEmailParameters) => Promise; /** * Authorizes a user with their email. * @param parameters The parameters for email authorization. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authorization fails. */ authorizeWithEmail: ( parameters: LoginEmailParameters ) => Promise; /** /** * Sends a verification code to the user's SMS. * @param parameters The parameters for sending the SMS code. * @throws {AuthError} If sending the SMS code fails. */ sendSMSCode: (parameters: PasswordlessSmsParameters) => Promise; /** * Authorizes a user with their SMS. * @param parameters The parameters for SMS authorization. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authorization fails. */ authorizeWithSMS: (parameters: LoginSmsParameters) => Promise; /** * Sends a multifactor challenge to the user. * @param parameters The parameters for the multifactor challenge. * @returns A promise that resolves when the challenge has been sent. * @throws {AuthError} If sending the challenge fails. */ sendMultifactorChallenge: ( parameters: MfaChallengeParameters ) => Promise; /** * Authorizes a user with out-of-band (OOB) authentication. * @param parameters The parameters for OOB authorization. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authorization fails. */ authorizeWithOOB: (parameters: LoginOobParameters) => Promise; /** * Authorizes a user with a one-time password (OTP). * @param parameters The parameters for OTP authorization. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authorization fails. */ authorizeWithOTP: (parameters: LoginOtpParameters) => Promise; /** * Authorizes a user with a recovery code. * @param parameters The parameters for recovery code authorization. * @returns A promise that resolves with the user's credentials. * @throws {AuthError} If the authorization fails. */ authorizeWithRecoveryCode: ( parameters: LoginRecoveryCodeParameters ) => Promise; // Token Management revokeRefreshToken: (parameters: RevokeOptions) => Promise; /** * Generates DPoP headers for making authenticated requests to custom APIs. * This method creates the necessary HTTP headers (Authorization and DPoP) to * securely bind the access token to a specific API request. * * @param params Parameters including the URL, HTTP method, access token, and token type. * @returns A promise that resolves to an object containing the required headers. * * @example * ```typescript * const credentials = await getCredentials(); * * if (credentials.tokenType === 'DPoP') { * const headers = await getDPoPHeaders({ * url: 'https://api.example.com/data', * method: 'GET', * accessToken: credentials.accessToken, * tokenType: credentials.tokenType * }); * * const response = await fetch('https://api.example.com/data', { headers }); * } * ``` */ getDPoPHeaders: ( params: DPoPHeadersParams ) => Promise>; /** * Obtains session transfer credentials for performing Native to Web SSO. * * @remarks * This method exchanges the stored refresh token for a session transfer token * that can be used to authenticate in web contexts without requiring the user * to log in again. The session transfer token can be passed as a cookie or * query parameter to the `/authorize` endpoint to establish a web session. * * Session transfer tokens are short-lived and expire after a few minutes. * Once expired, they can no longer be used for web SSO. * * If Refresh Token Rotation is enabled, this method will also update the stored * credentials with new tokens (ID token and refresh token) returned from the * token exchange. * * **Platform specific:** This method is only available on native platforms (iOS/Android). * On web, it will throw an error. * * @param parameters Optional additional parameters to pass to the token exchange. * @param headers Optional additional headers to include in the token exchange request. **iOS only** - this parameter is ignored on Android. * @returns A promise that resolves with the session transfer credentials. * * @example * ```typescript * // Get session transfer credentials * const ssoCredentials = await getSSOCredentials(); * * // Option 1: Use as a cookie (recommended) * const cookie = `auth0_session_transfer_token=${ssoCredentials.sessionTransferToken}; path=/; domain=.yourdomain.com; secure; httponly`; * document.cookie = cookie; * window.location.href = `https://yourdomain.com/authorize?client_id=${clientId}&...`; * * // Option 2: Use as a query parameter * const authorizeUrl = `https://yourdomain.com/authorize?session_transfer_token=${ssoCredentials.sessionTransferToken}&client_id=${clientId}&...`; * window.location.href = authorizeUrl; * ``` * * @see https://auth0.com/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web */ getSSOCredentials: ( parameters?: Record, headers?: Record ) => Promise; /** * Exchanges a refresh token for session transfer credentials via the Authentication API. * * @remarks * This method calls the Auth0 `/oauth/token` endpoint directly to exchange a refresh token * for a session transfer token. Unlike `getSSOCredentials()` which uses the Credentials Manager, * this method is intended for apps that manage their own tokens. * * **Platform specific:** This method is only available on native platforms (iOS/Android). * On web, it will throw an error. * * @param parameters The parameters containing the refresh token to exchange. * @returns A promise that resolves with the session transfer credentials. * * @see https://auth0.com/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web */ ssoExchange: ( parameters: SSOExchangeParameters ) => Promise; } const stub = (): any => { throw new Error('You forgot to wrap your component in .'); }; const initialContext: Auth0ContextInterface = { user: null, error: null, isLoading: true, authorize: stub, clearSession: stub, saveCredentials: stub, getCredentials: stub, clearCredentials: stub, hasValidCredentials: stub, getApiCredentials: stub, clearApiCredentials: stub, loginWithPasswordRealm: stub, cancelWebAuth: stub, authorizeWithExchange: stub, createUser: stub, authorizeWithRecoveryCode: stub, authorizeWithExchangeNativeSocial: stub, customTokenExchange: stub, sendEmailCode: stub, sendSMSCode: stub, authorizeWithEmail: stub, authorizeWithSMS: stub, sendMultifactorChallenge: stub, authorizeWithOOB: stub, authorizeWithOTP: stub, resetPassword: stub, revokeRefreshToken: stub, getDPoPHeaders: stub, getSSOCredentials: stub, ssoExchange: stub, }; export const Auth0Context = createContext(initialContext);