@entrustcorp/idaas-auth-js
Version:
IDaaS Authentication SDK for SPA applications
1,160 lines (1,124 loc) • 55.2 kB
TypeScript
import type { JWTPayload } from 'jose';
/**
* All information associated with a single access token.
*/
declare interface AccessToken {
accessToken: string;
expiresAt: number;
refreshToken?: string;
audience?: string;
scope: string;
maxAgeExpiry?: number;
acr?: string;
}
/**
* Convenience authentication client for fixed authentication methods.
*
* This client provides simplified methods for specific authentication types (password, OTP, passkey, etc.)
* when you want to bypass risk-based evaluation and use a specific authentication method directly.
*
* **Use cases:**
* - Login pages with traditional username/password forms
* - Passwordless authentication flows with a specific method (e.g., passkey-only)
* - Applications that don't require dynamic authentication based on context
*
* **When to use this vs RbaClient:**
* - Use `AuthClient` when you know which authentication method you want to use
* - Use `RbaClient` when you want the identity provider to dynamically select authentication
* methods based on risk and Resource Rules
*
* Under the hood, these methods use `RbaClient` with `strict: true` and a specified
* `preferredAuthenticationMethod` to force a specific authentication method.
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/auth.md Convenience Auth Guide}
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/choosing-an-approach.md Choosing an Approach}
*/
declare class AuthClient {
#private;
constructor(rbaClient: RbaClient);
/**
* Authenticates a user with username and password.
*
* This method bypasses risk-based evaluation and directly requests password authentication.
* It's ideal for traditional login forms where you want a consistent password-based experience.
*
* The method automatically:
* 1. Requests a PASSWORD challenge from the identity provider
* 2. Submits the provided password
* 3. Stores tokens upon successful authentication
*
* **When to use:**
* - Traditional login pages with username/password fields
* - Applications that require password authentication for specific workflows
* - Testing and development scenarios
*
* @param userId The user's unique identifier (email, username, etc.)
* @param password The user's password
* @returns Authentication response with `authenticationCompleted: true` on success
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/auth.md Convenience Auth Guide}
*/
password(userId: string, password: string): Promise<AuthenticationResponse>;
/**
* Authenticate using Entrust Soft Token.
*
* Modes:
* - push === false: Issues a TOKEN challenge (OTP). Caller must later call submitChallenge with the user’s code.
* - push === true && mutualChallenge === false: Starts a TOKENPUSH challenge and immediately polls until completion; returns the final AuthenticationResponse.
* - push === true && mutualChallenge === true: Starts a TOKENPUSH challenge with mutual challenge enabled; returns the initial response containing the mutual challenge. Caller must then call poll() to await completion.
*
* **Mutual Challenge**: When enabled, the user must verify a challenge code displayed on the authentication device
* to protect against push bombing attacks (where attackers spam push notifications hoping the user accidentally approves).
* The `mutualChallenge` option is ignored unless `push` is true.
*
*
* @param userId The user ID to authenticate.
* @param options Soft token authentication options
* @param options.push Determines if push authentication (true) or standard token authentication (false) should be used. Default false.
* @param options.mutualChallenge Enables mutual challenge for push. Only valid if push is true. Default false.
* @returns AuthenticationResponse:
* - Final result (success/failure) for plain TOKENPUSH (no mutual challenge).
* - Initial challenge response for TOKENPUSH with mutual challenge (requires poll).
* - Initial challenge response for TOKEN (requires submitChallenge with OTP).
* @throws On request/poll errors.
*/
softToken(userId: string, { mutualChallenge, push }?: SoftTokenOptions): Promise<AuthenticationResponse>;
/**
* Starts a GRID challenge.
* Response includes gridChallenge.challenge: [{ row: 0, column: 1 }, ...] (one entry per required cell).
* Prompt the user for the contents of the cell at each coordinate (in order) to build the code, then call the submit method with their code (e.g idaasClient.auth.submit({ response: 'A6N3D5' })).
*
* @param userId The user ID to authenticate.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the gridChallenge to display to the user.
*/
grid(userId: string): Promise<AuthenticationResponse>;
/**
* Authenticates a user with a passkey (WebAuthn/FIDO2).
*
* Supports two modes:
* - **With userId**: Uses FIDO authentication (user must have registered a passkey)
* - **Without userId**: Uses usernameless/discoverable credential (PASSKEY)
*
* This method handles the complete passkey flow:
* 1. Requests an appropriate challenge (FIDO or PASSKEY)
* 2. Invokes the browser's passkey UI (`navigator.credentials.get()`)
* 3. Submits the WebAuthn credential automatically
* 4. Stores tokens upon successful authentication
*
* **Browser support:**
* Requires a browser with WebAuthn support. The method checks for support automatically
* and throws an error if passkeys are not available.
*
* **When to use:**
* - Passwordless authentication flows
* - Security key authentication
* - Biometric authentication (Face ID, Touch ID, Windows Hello)
*
* @param userId Optional user identifier (omit for usernameless authentication)
* @returns Authentication response with `authenticationCompleted: true` on success
* @throws {Error} If browser doesn't support passkeys
* @throws {Error} If user cancels the passkey ceremony
* @throws {Error} If no credential is returned
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/auth.md Convenience Auth Guide}
*/
passkey(userId?: string): Promise<AuthenticationResponse | undefined>;
/**
* Starts a KBA (knowledge-based) challenge.
* Response includes kbaChallenge.userQuestions: [{ question: string }, ...].
* Gather answers and call submit({ kbaChallengeAnswers: ['answer1', 'answer2', ...]}).
* Order of answers must match order of questions received.
*
* @param userId The user ID to authenticate.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the KBA challenge questions to display to the user.
*/
kba(userId: string): Promise<AuthenticationResponse>;
/**
* Authenticate using a temporary access code.
* Requests a TEMP_ACCESS_CODE challenge, then immediately submits the provided code.
*
* @param userId The user ID to authenticate.
* @param tempAccessCode The temporary access code to submit.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
*/
tempAccessCode(userId: string, tempAccessCode: string): Promise<AuthenticationResponse>;
/**
* Requests an One-Time Password (OTP) to be sent to the user.
*
* This method initiates OTP authentication by requesting a time-based code to be delivered
* to the user via their configured delivery method (SMS, email, or voice call).
*
* After calling this method, prompt the user to enter the OTP they received, then call
* `idaasClient.auth.submit({ response: '123456' })` to complete authentication.
*
* **Delivery options:**
* - **SMS**: Code sent via text message (default for most configurations)
* - **EMAIL**: Code sent via email
* - **VOICE**: Code delivered via automated phone call
*
* You can optionally specify a delivery type and/or attribute to override the user's default.
*
* **When to use:**
* - Two-factor authentication (2FA) scenarios
* - Passwordless authentication with OTP
* - Account verification flows
*
* @param userId The user's unique identifier
* @param options OTP delivery configuration (type and attribute)
* @returns Authentication response containing the challenge (requires submission)
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/auth.md Convenience Auth Guide}
*/
otp(userId: string, { otpDeliveryType, otpDeliveryAttribute }?: OtpOptions): Promise<AuthenticationResponse>;
/**
* Authenticate using Magic Link.
* Requests a MAGICLINK challenge, then immediately starts polling for completion.
*
* @param userId The user ID to authenticate.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
*/
magicLink(userId: string): Promise<AuthenticationResponse>;
/**
* Authenticate using Smart Credential Push.
* Requests a SMARTCREDENTIALPUSH challenge, then immediately starts polling for completion.
*
* @param userId The user ID to authenticate.
* @param options Smart credential authentication options
* @param options.summary The summary to display in the push notification.
* @param options.pushMessageIdentifier The identifier to retrieve customized SDK push message configuration.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
*/
smartCredential(userId: string, { summary, pushMessageIdentifier }?: SmartCredentialOptions): Promise<AuthenticationResponse>;
/**
* Authenticate using Face.
* Requests a FACE challenge, then initializes the Onfido Web SDK and polls for completion on onComplete.
*
* Requirements:
* - Optional peer dependency: Install 'onfido-sdk-ui' to use this method:
* npm install onfido-sdk-ui
* (It is declared as an optional peer dependency; projects not using face auth can omit it.)
* - DOM container: Ensure a <div id="onfido-mount"></div> exists in the DOM before calling. The SDK mounts its UI there.
*
* Flow:
* 1. requestChallenge(FACE) returns faceChallenge with sdkToken and workflowRunId.
* 2. Onfido.init is called with those values and containerId 'onfido-mount'.
* 3. On onComplete the method polls for final authentication status and resolves with the AuthenticationResponse.
*
* @param userId The user ID to authenticate.
* @param mutualChallenge Determines if the user must answer a mutual challenge for and FACE authenticator.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
* @throws If faceChallenge is missing, Onfido initialization fails, or polling fails.
*/
faceBiometric(userId: string, { mutualChallenge }?: FaceBiometricOptions): Promise<AuthenticationResponse>;
/**
* Submits a response to an authentication challenge.
* Processes authentication responses and completes the authentication if successful.
* @param params Authentication submission parameters
* @param params.response The user's response to the authentication challenge.
* @param params.passkeyResponse The publicKeyCredential returned from navigator.credentials.get(credentialRequestOptions).
* @param params.kbaChallengeAnswers The user's answers to the KBA challenge questions. Answers must be in the order of the questions returned when requesting the challenge.
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
*/
submit({ response, passkeyResponse, kbaChallengeAnswers, }: AuthenticationSubmissionParams): Promise<AuthenticationResponse>;
logout(): Promise<void>;
/**
* Polls the authentication provider to check for completion of an ongoing authentication process.
* Useful for authentication flows that may complete asynchronously (e.g., token push authentication).
*
* @returns AuthenticationResponse containing information regarding the authentication request. Includes the authenticationCompleted flag to indicate successful authentication.
*/
poll(): Promise<AuthenticationResponse>;
/**
* Cancels an ongoing authentication challenge.
* Terminates the current authentication transaction and cleans up any pending state.
*/
cancel(): Promise<void>;
}
/**
* The configurable options when requesting an authentication challenge.
*/
export declare interface AuthenticationRequestParams {
/**
* The user ID of the user to request the challenge for.
*/
userId?: string;
/**
* The user's password to submit for MFA flows.
*/
password?: string;
/**
* The preferred method of authentication.
*/
preferredAuthenticationMethod?: IdaasAuthenticationMethod;
/**
* Determines if the preferred authentication method must be used.
*/
strict?: boolean;
/**
* Options available during OTP authentication.
*/
otpOptions?: OtpOptions;
/**
* Options available during TOKENPUSH authentication.
*/
softTokenPushOptions?: SoftTokenPushOptions;
/**
* Options available during SMARTCREDENTIALPUSH authentication.
*/
smartCredentialOptions?: SmartCredentialOptions;
/**
* Options available during FACE authentication.
*/
faceBiometricOptions?: FaceBiometricOptions;
/**
* The transaction details of the request.
*/
transactionDetails?: TransactionDetail[];
}
/**
* The response from IDaaS when requesting or submitting an authentication challenge.
*/
export declare interface AuthenticationResponse {
/**
* The authorization token (IDaaS JWT).
*/
token?: string;
/**
* A flag indicating if authentication has been completed.
*/
authenticationCompleted?: boolean;
/**
* The second factor authenticator that will be used.
*/
secondFactorMethod?: IdaasAuthenticationMethod;
/**
* The method of authentication that will be used.
*/
method?: IdaasAuthenticationMethod;
/**
* A flag indicating if `poll` should be called.
*/
pollForCompletion?: boolean;
/**
* The user ID of the authenticated user.
*/
userId?: string;
/**
* Parameters required for completing the `GRID` authentication method.
*/
gridChallenge?: GridChallenge;
/**
* Parameters required for completing the `KBA` authentication method.
*/
kbaChallenge?: KbaChallenge;
/**
* Parameters required for completing the `FACE` authentication method.
*/
faceChallenge?: FaceChallenge;
/**
* Parameters defining the behaviour of the `TEMP_ACCESS_CODE` authentication method.
*/
tempAccessCodeChallenge?: TempAccessCodeChallenge;
/**
* Push authentication mutual challenge for token or Face Biometric.
*/
pushMutualChallenge?: string;
/**
* The PublicKeyCredentialRequestOptions to be passed in the publicKey field to the navigator.credential.get() call.
*/
passkeyChallenge?: PublicKeyCredentialRequestOptions;
}
/**
* The configurable options when submitting a response to an authentication challenge.
*/
export declare interface AuthenticationSubmissionParams {
/**
* The user's response to the authentication challenge.
*/
response?: string;
/**
* The user's answers to the KBA challenge questions.
* Answers must be in the order of the questions returned when requesting the challenge.
*/
kbaChallengeAnswers?: string[];
/**
* The credential returned from navigator.credentials.get(credentialRequestOptions).
*/
passkeyResponse?: PublicKeyCredential;
}
/**
* The parameters that are created during the creation of the authorization URL.
* @interface ClientParams
* @member nonce A random generated string used to validate the OIDC flow
* @member codeVerifier A random generated string that is hashed and encoded for use as a code_challenge
* @member redirectUri The URI to redirect to upon successful login to the IDP server
* @member state A random generated string used to validate the OIDC flow
*/
declare interface ClientParams {
nonce: string;
codeVerifier: string;
redirectUri: string;
state: string;
}
/**
* The configurable options when requesting a FACE authentication challenge.
*/
export declare interface FaceBiometricOptions {
/**
* Determines if the user must answer a mutual challenge for the FACE authenticator.
*/
mutualChallenge?: boolean;
}
/**
* Parameters returned to initialize a Face Biometric authenticator.
*/
export declare type FaceChallenge = {
/**
* Which device to use for registration and authentication.
*/
device?: 'WEB' | 'MOBILE';
/**
* The ID of the Face Biometric to get.
*/
id?: string;
/**
* QR Code to use to launch the mobile flow.
*/
qrCode?: string;
/**
* The SDK token generated for the user.
*/
sdkToken?: string;
/**
* Workflow run ID to use for the user.
*/
workflowRunId?: string;
};
/**
* If the authentication challenge is of type FIDO, the FIDOChallenge will contain the FIDO challenge parameters that must be passed to the FIDO token to complete authentication.
*/
export declare type FidoChallenge = {
/**
* The list of IDs of the FIDO tokens registered for the user. Each value is base-64 encoded.
*/
allowCredentials?: Array<string>;
/**
* A random challenge. It is a base-64 encoded value.
*/
challenge: string;
/**
* The number of seconds that the client will wait for the FIDO token to respond. This field is deprecated, use 'timeoutMillis' instead.
*
* @deprecated
*/
timeout: number;
/**
* The number of milliseconds that the client will wait for the FIDO token to respond.
*/
timeoutMillis: number;
};
/**
* If the authentication challenge is of type grid, the GridChallenge object will contain the grid challenge that the end user must answer.
*/
export declare type GridChallenge = {
/**
* The cellAlphabets value specifies the characters that are valid for the cells in the grid challenge.
*/
cellAlphabets: string;
/**
* The grid challenge specifies a list of grid cells that the user must answer in their challenge.
*/
challenge: Array<GridChallengeCell>;
/**
* The grid details.
*/
gridInfo: Array<GridInfo>;
/**
* The numCharsPerCell value specifies the number of characters expected in the response for each cell as defined by current settings.
*/
numCharsPerCell: number;
};
/**
* A GridChallengeCell specifies one cell in a grid by its row and column coordinates. Normally a grid challenge cell is displayed using letters for the column and numbers for the row. For example, a cell with the value 0,0 will be displayed as A1.
*/
declare type GridChallengeCell = {
/**
* The column within the grid starting at 0.
*/
column: number;
/**
* The row within the grid starting at 0.
*/
row: number;
};
/**
* Details about the grid.
*/
declare type GridInfo = {
/**
* The expiry date of the grid. Null value indicates the grid will never expire.
*/
expiryDate?: string;
/**
* The serial number of the grid that can be used to answer this challenge.
*/
serialNumber: string;
};
export declare type IdaasAuthenticationMethod = "PASSWORD" | "KBA" | "TEMP_ACCESS_CODE" | "OTP" | "GRID" | "TOKEN" | "TOKENPUSH" | "FIDO" | "SMARTCREDENTIALPUSH" | "PASSWORD_AND_SECONDFACTOR" | "MAGICLINK" | "PASSKEY" | "FACE" | "EXTERNAL";
/**
* The main client class for interacting with IDaaS authentication services.
* Provides methods for OIDC authentication flows and RBA challenge handling.
* @public
*/
export declare class IdaasClient {
#private;
/**
* Creates a new IdaasClient instance for handling OIDC authentication flows.
*
* @param options Configuration options for the client including issuer URL, client ID, and storage type
* @param tokenOptions Default token options including audience, scope, and refresh token settings
*/
constructor({ issuerUrl, clientId, storageType, allowedIdTokenSigningAlgorithms }: IdaasClientOptions, tokenOptions?: TokenOptions);
/**
* Provides access to IDaaS hosted OIDC methods.
*
* Use this when you want Entrust to host the entire login UI. It handles PKCE, redirects, and logout
* for a quick hosted authentication experience.
*
* Available methods:
* - `login(options?, tokenOptions?)` - Initiate login via redirect or popup
* - `logout(options?)` - Log user out with optional redirect
* - `handleRedirect()` - Process OAuth callback after redirect
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/oidc.md OIDC Guide}
*/
get oidc(): OidcClient;
/**
* Provides access to self-hosted Risk-Based Authentication (RBA) methods.
*
* Use this when building your own UI and need full control over multi-factor and risk-based challenges.
* Requires Resource Rules to be configured in IDaaS for risk evaluation.
*
* Available methods:
* - `requestChallenge(params?, tokenOptions?)` - Request authentication challenge with risk evaluation
* - `submitChallenge(params)` - Submit user response to challenge
* - `poll()` - Poll for asynchronous authentication completion
* - `cancel()` - Cancel ongoing authentication
* - `logout()` - End user session
*
* **Note:** Supply the user's identifier (`userId`) in `AuthenticationRequestParams` unless the
* authenticator explicitly allows anonymous flows (e.g., passkey with discoverable credentials).
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
get rba(): RbaClient;
/**
* Provides access to self-hosted auth convenience methods.
*
* Use these simplified helpers when you want custom UI but have a fixed authentication method
* configured in IDaaS (not using Resource Rules for risk-based decisions).
*
* Available methods:
* - `password(userId, password)` - Password authentication
* - `softToken(userId, options?)` - Soft token (TOTP or push)
* - `grid(userId)` - Grid card authentication
* - `passkey(userId?)` - WebAuthn/FIDO2 passkey (omit userId for discoverable credentials)
* - `kba(userId)` - Knowledge-based authentication
* - `tempAccessCode(userId, code)` - Temporary access code
* - `otp(userId, options?)` - One-time password
* - `smartCredential(userId, options?)` - Smart credential push
* - `faceBiometric(userId, options?)` - Face biometric authentication
* - `magicLink(userId)` - Magic link authentication
* - `submit(params?)` - Submit challenge response
* - `poll()` - Poll for completion
* - `cancel()` - Cancel authentication
* - `logout()` - End session
*
* **Note:** Almost every convenience helper expects `userId` as the first argument.
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/auth.md Convenience Auth Guide}
*/
get auth(): AuthClient;
/**
* @private used to access the storage manager for testing purposes.
*/
private get storageManager();
/**
* Checks if the user is currently authenticated by verifying the presence of a valid ID token.
*
* @returns `true` when an ID token exists, `false` otherwise
*/
isAuthenticated(): boolean;
/**
* Retrieves decoded ID token claims containing user information.
*
* The ID token is a JWT that contains standard OIDC claims about the authenticated user
* such as `sub` (subject/user ID), `email`, `name`, etc.
*
* @returns Decoded ID token claims, or `null` if no ID token exists
*/
getIdTokenClaims(): UserClaims | null;
/**
* Retrieves a cached access token matching the specified criteria.
*
* If the token is expired and a refresh token is available (subject to tenant configuration),
* the SDK automatically performs a token refresh.
*
* @param options Token options to match (audience, scope, acrValues)
* @returns Access token string, or `null` when no matching session exists
* @throws Error if the refresh/token exchange fails
*/
getAccessToken({ audience, scope, acrValues, }?: TokenOptions): Promise<string | null>;
/**
* Retrieves user claims from the OpenID Provider using the userinfo endpoint.
*
* This method fetches fresh user information from the identity provider, as opposed to
* `getIdTokenClaims()` which returns cached claims from the ID token.
*
* @param accessToken Optional access token to use. When provided, its scopes determine the claims
* returned from the userinfo endpoint. If not provided, the access token with default scopes and
* audience will be used if available.
* @returns User claims from the OpenID Provider, or `null` if unavailable
*/
getUserInfo(accessToken?: string): Promise<UserClaims | null>;
/**
* Parses RFC 9470 / RFC 6750 authentication requirements from a protected resource response.
*
* When a protected resource returns an HTTP response with a `WWW-Authenticate: Bearer`
* header containing `error="insufficient_user_authentication"` (RFC 9470) or
* `error="insufficient_scope"` (RFC 6750), this method extracts the requested
* `acr_values`, `max_age`, and `scope` requirements from that header.
*
* @param response - The HTTP response from the protected resource containing the `WWW-Authenticate` header
* @returns Parsed authentication requirements from the response header
* @throws Error If the response has no `WWW-Authenticate` header
* @throws Error If the `WWW-Authenticate` header does not indicate a recognized Bearer challenge
*
* See [RFC 9470 - Step-Up Authentication Challenge Protocol](https://datatracker.ietf.org/doc/html/rfc9470)
* and [RFC 6750 - Bearer Token Usage](https://datatracker.ietf.org/doc/html/rfc6750).
*/
parseResponse(response: Response): TokenOptions;
}
/**
* The configurable options of the IdaasClient.
*/
export declare interface IdaasClientOptions {
/**
* The issuer to be used for validation of JWTs and for fetching API endpoints, typically `https://{yourIdaasDomain}.region.trustedauth.com/api/oidc`.
*/
issuerUrl: string;
/**
* The Client ID found on your IDaaS Application settings page.
*/
clientId: string;
/**
* The storage mechanism to use for ID and access tokens.
*
* @default "memory"
*/
storageType?: "memory" | "localstorage";
/**
* The allowed algorithms for validating ID token signatures.
*
* Defaults to: `PS256 PS384 PS512 RS256 RS384 RS512 EC256 ES384 ES512`.
*
* Provide this to restrict validation to a specific subset.
*/
allowedIdTokenSigningAlgorithms?: string[];
}
/**
* Services class to provide shared functionality to OIDC and RBA clients
* without exposing the entire IdaasClient implementation
*/
declare class IdaasContext {
#private;
constructor({ issuerUrl, clientId, tokenOptions, allowedIdTokenSigningAlgorithms, }: {
issuerUrl: string;
clientId: string;
tokenOptions: NormalizedTokenOptions;
allowedIdTokenSigningAlgorithms?: string[];
});
get issuerUrl(): string;
get clientId(): string;
get tokenOptions(): NormalizedTokenOptions;
get allowedIdTokenSigningAlgorithms(): string[] | undefined;
/**
* Get the OpenID configuration for the provider
*/
getConfig(): Promise<OidcConfig>;
}
/**
* Contains the IDaaS Session Token.
*/
declare interface IdaasSessionToken {
token: string;
}
/**
* Contains the encoded and decoded versions of an id token.
*/
declare interface IdToken {
encoded: string;
decoded: JWTPayload;
}
/**
* Knowledge-based authenticator required for authentication to Identity as a Service
*/
export declare type KbaChallenge = {
id?: string;
userQuestions: Array<UserQuestion>;
};
/**
* Machine authenticator required to complete authentication challenge
*/
declare type MachineAuthenticator = {
/**
* The device fingerprint if it's required during Machine authentication. It will always be null when returned from IDaaS as part of the response body.
*/
fingerprint?: string;
/**
* machineNonce
*/
machineNonce?: string;
/**
* sequenceNonce
*/
sequenceNonce?: string;
};
/**
* Normalized token options with defaults applied.
* All properties except audience & maxAge are required.
*/
declare type NormalizedTokenOptions = Required<Omit<TokenOptions, "audience" | "maxAge">> & Pick<TokenOptions, "audience" | "maxAge">;
/**
* This class handles authorization for OIDC flows using both popup
* and redirect authentication patterns. It manages the entire OIDC ceremony
* including authorization URL generation, token exchange, validation, and processing
* redirect callbacks.
*
* Contains three main methods: login, logout, and handleRedirect.
*/
declare class OidcClient {
#private;
constructor(context: IdaasContext, storageManager: StorageManager_2);
/**
* Initiates the OIDC authorization code flow to authenticate the user.
*
* Supports two modes:
* - **Popup mode** (`popup: true`): Opens a popup window for authentication, automatically handles the callback,
* and returns the access token
* - **Redirect mode** (`popup: false`): Redirects the current page to the identity provider. Your application
* must call `handleRedirect()` at the `redirectUri` to complete the flow
*
* The flow uses PKCE (Proof Key for Code Exchange) for security and obtains:
* - Access token (always)
* - ID token (always)
* - Refresh token (optional, if `useRefreshToken: true`)
*
* @param options Login options including popup mode and redirect URI
* @param tokenOptions Token request options (audience, scope, refresh token, ACR values)
* @returns The access token if using popup mode, otherwise `null`
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/oidc.md OIDC Guide}
* */
login({ redirectUri, popup }?: OidcLoginOptions, tokenOptions?: TokenOptions): Promise<string | null>;
/**
* Logs the user out by clearing the local session and redirecting to the identity provider's logout endpoint.
*
* This method:
* 1. Removes all stored tokens (access, ID, and refresh) from local storage
* 2. Redirects the browser to the identity provider's `end_session_endpoint`
* 3. Optionally redirects back to your application after logout completes
*
* After logout, the user's session with the identity provider is terminated. If `redirectUri` is provided,
* the identity provider will redirect the user back to that URI after logout.
*
* @param options Logout options with optional redirect URI
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/oidc.md OIDC Guide}
*/
logout({ redirectUri }?: OidcLogoutOptions): Promise<void>;
/**
* Completes the OIDC authorization code flow after redirect from the identity provider.
*
* Call this method at your application's `redirectUri` to:
* 1. Parse the authorization code from the URL query parameters
* 2. Exchange the code for tokens (access, ID, and optionally refresh)
* 3. Validate and store the tokens
*
* This method should be called early in your application initialization at the redirect URI path,
* typically before rendering your main application UI.
*
* **Important**: Only required when using redirect mode (`popup: false` in `login()`).
* Popup mode handles the callback automatically.
*
* @returns `null` after processing the redirect, or `null` if current URL is not an OAuth callback
* @throws {Error} If client state cannot be recovered from storage
* @throws {Error} If authorization response contains an error
* @throws {Error} If token validation fails
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/oidc.md OIDC Guide}
*/
handleRedirect(): Promise<null>;
}
/**
* Interface describing the OpenID provider metadata retrieved during OIDC discovery.
*
* This is a non-exhaustive interface, and only describes the required fields and those relevant for this client implementation.
* See more at: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
*/
declare interface OidcConfig {
issuer: string;
authorization_endpoint: string;
token_endpoint: string;
userinfo_endpoint: string;
jwks_uri: string;
registration_endpoint: string;
scopes_supported: string[];
response_modes_supported?: string[];
grant_types_supported?: string[];
acr_values_supported?: string[];
subject_types_supported: string[];
id_token_signing_alg_values_supported: string[];
claims_supported: string[];
end_session_endpoint: string;
}
/**
* The configurable options specific to the OIDC `login` method.
*/
export declare interface OidcLoginOptions {
/**
* The URI to be redirected to after a successful login. The default value is the current page.
* This URI must be included in the `Login Redirect URI(s)` field in your IDaaS client application settings.
*/
redirectUri?: string;
/**
* Determines the method of login that will be used to authenticate the user.
* The default setting is `false`.
*/
popup?: boolean;
}
/**
* The configurable options for the Logout method.
*/
export declare interface OidcLogoutOptions {
/**
* The URI to be redirected to after a successful logout. This URI must be included in the `Logout Redirect URI(s)` field in your IDaaS client application settings.
*/
redirectUri?: string;
}
export declare interface OtpOptions {
/**
* The delivery type for the OTP challenge.
*/
otpDeliveryType?: UserChallengeParameters["otpDeliveryType"];
/**
* The name of the delivery attribute to use for the OTP challenge, such as a "business-email".
*/
otpDeliveryAttribute?: string;
}
/**
* Passthrough authenticator parameters
*/
declare type PassthroughAuthenticatorParms = {
/**
* The list of placeholders.
*/
passthroughAuthenticatorPlaceholders?: Array<PassthroughAuthenticatorPlaceholder>;
};
/**
* Passthrough authenticator placeholder
*/
declare type PassthroughAuthenticatorPlaceholder = {
/**
* The placeholder name.
*/
name: string;
/**
* The placeholder value.
*/
value: string;
};
/**
* Risk-Based Authentication (RBA) client for self-hosted authentication flows.
*
* This client enables you to build custom authentication UI within your application by handling
* challenge-response authentication flows. It manages the complete authentication transaction
* lifecycle: challenge requests, response submissions, asynchronous polling, and cancellation.
*
* **Important**: RBA authentication requires your application to be configured with **Resource Rules**
* in the IDaaS portal. Resource Rules define which authentication methods are required based on
* contextual risk factors like IP address, device fingerprint, transaction amount, etc.
*
* Main methods:
* - `requestChallenge()`: Initiate authentication and receive a challenge
* - `submitChallenge()`: Submit user response to the challenge
* - `poll()`: Check for async completion (e.g., push notifications)
* - `cancel()`: Cancel an ongoing authentication transaction
* - `logout()`: End the session and revoke tokens
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/choosing-an-approach.md Choosing an Approach}
*/
declare class RbaClient {
#private;
constructor(context: IdaasContext, storageManager: StorageManager_2);
/**
* Initiates a risk-based authentication challenge based on configured Resource Rules.
*
* This method starts an authentication transaction by sending contextual information to the
* identity provider, which evaluates risk and returns an appropriate authentication challenge
* based on your configured Resource Rules.
*
* **Key features:**
* - Automatic risk evaluation based on transaction details (IP address, device, transaction amount, etc.)
* - Dynamic authentication method selection (password, OTP, push, biometric, etc.)
* - Support for step-up authentication scenarios
*
* The response indicates:
* - Which authentication method is required
* - Whether the method requires user interaction (`pollForCompletion: false`) or is asynchronous (`pollForCompletion: true`)
* - Challenge details (e.g., grid coordinates, KBA questions, FIDO options)
*
* @param options Authentication request parameters including userId and transactionDetails
* @param tokenOptions Token request options (audience, scope, ACR values)
* @returns Authentication response containing the challenge and method details
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
requestChallenge(options?: AuthenticationRequestParams, tokenOptions?: TokenOptions): Promise<AuthenticationResponse>;
/**
* Submits the user's response to an authentication challenge.
*
* After receiving a challenge from `requestChallenge()`, use this method to submit the user's
* authentication response (e.g., password, OTP code, grid coordinates, KBA answers).
*
* The response indicates whether:
* - Authentication completed successfully (`authenticationCompleted: true`)
* - Additional authentication is required (step-up scenario)
* - Authentication failed
*
* Upon successful completion, tokens are automatically stored and can be retrieved via
* `getAccessToken()` and `getIdTokenClaims()`.
*
* @param options Authentication submission parameters with the user's response data
* @returns Authentication response indicating completion status or next challenge
* @throws {Error} If no authentication transaction is in progress
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
submitChallenge(options?: AuthenticationSubmissionParams): Promise<AuthenticationResponse>;
/**
* Logs the user out and terminates their session.
*
* This method:
* 1. Revokes the session token with the identity provider (server-side logout)
* 2. Clears all stored tokens (access, ID, and refresh) from local storage
* 3. Resets the current authentication transaction
*
* After logout, the user must authenticate again via `requestChallenge()`.
*
* **Note**: Unlike OIDC logout, this method does not redirect the browser.
* It completes silently and returns a Promise.
*
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
logout(): Promise<void>;
/**
* Polls for completion of an asynchronous authentication flow.
*
* Some authentication methods complete asynchronously without requiring `submitChallenge()`:
* - Push notifications (user approves on mobile device)
* - Email magic links (user clicks link in email)
* - SMS magic links (user clicks link in SMS)
*
* When `pollForCompletion: true` in the challenge response, call this method repeatedly
* (e.g., every 2-3 seconds) to check if the user has completed authentication on their device.
*
* **Polling behavior:**
* - Returns `authenticationCompleted: false` while waiting for user action
* - Returns `authenticationCompleted: true` when authentication succeeds
* - Automatically stores tokens upon successful completion
*
* @returns Authentication response indicating completion status
* @throws {Error} If no authentication transaction is in progress
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
poll(): Promise<AuthenticationResponse>;
/**
* Cancels the current authentication transaction.
*
* Use this method to abandon an in-progress authentication flow, for example:
* - User clicks "Cancel" button during authentication
* - User navigates away from authentication page
* - Authentication timeout occurs
*
* This terminates the transaction server-side and cleans up any pending state.
* After cancellation, you must call `requestChallenge()` again to start a new authentication flow.
*
* @throws {Error} If no authentication transaction is in progress
* @see {@link https://github.com/EntrustCorporation/idaas-auth-js/blob/main/docs/guides/rba.md RBA Guide}
*/
cancel(): Promise<void>;
}
/**
* Request detail items.
*/
declare type RequestDetail = {
/**
* The browser associated with the request.
*/
browser?: string;
/**
* The OS associated with the request.
*/
os?: string;
};
/**
* Options for smart credential authentication.
*/
export declare interface SmartCredentialOptions {
/**
* The push authentication challenge that appears in the user's mobile application.
*/
summary?: string;
/**
* Defines an identifier to retrieve customized SDK push message configuration.
*/
pushMessageIdentifier?: string;
}
/**
* The configurable options when requesting a TOKEN/TOKENPUSH authentication challenge.
*/
export declare interface SoftTokenOptions extends SoftTokenPushOptions {
/**
* Determines if push authentication (true) or standard token authentication (false) should be used. Default false.
*/
push?: boolean;
}
/**
* The configurable options when requesting a TOKENPUSH authentication challenge.
*/
export declare interface SoftTokenPushOptions {
/**
* Determines if the user must answer a mutual challenge for the TOKENPUSH authenticator.
*/
mutualChallenge?: boolean;
}
declare class StorageManager_2 {
#private;
constructor(clientId: string, storageType: "memory" | "localstorage");
/**
* Save ClientParams in local storage that are required to continue the OIDC auth flow on redirect from IDP login.
* @param data The ClientParams that were generated during the generate the Authorization URL.
*/
saveClientParams(data: ClientParams): void;
/**
* Save the IDaaS session token in storage.
* @param data The IDaaS session token.
*/
saveIdaasSessionToken(data: IdaasSessionToken): void;
/**
* Save information about the id token in storage.
* @param data The encoded and decoded id token.
*/
saveIdToken(data: IdToken): void;
/**
* Save the token params in local storage.
* @param data the token params to be saved.
*/
saveTokenParams(data: TokenParams): void;
/**
* Save access tokens in local storage.
* @param data the access token to be saved.
*/
saveAccessToken(data: AccessToken): void;
/**
* Remove an access token from storage.
* @param removedToken the token to be removed.
*/
removeAccessToken(removedToken: AccessToken): void;
/**
* Removes expired token from storage.
*/
removeExpiredTokens(): void;
/**
* Clears the stored token params.
*/
removeTokenParams(): void;
/**
* Retrieves the ClientParams stored in local storage.
* @returns The ClientParams.
*/
getClientParams(): ClientParams | undefined;
/**
* Retrieves the access tokens stored in local storage.
* @returns The array of access tokens.
*/
getAccessTokens(): AccessToken[];
/**
* Retrieves the stored token params.
* @returns The TokenParams object stored.
*/
getTokenParams(): TokenParams | undefined;
/**
* Retrieves the information about the id token stored in local storage.
* @returns The idToken object stored.
*/
getIdToken(): IdToken | undefined;
/**
* Retrieves the information about the IDaaS session token stored in storage.
* @returns IDaaS session token object if stored, otherwise undefined.
*/
getIdaasSessionToken(): IdaasSessionToken | undefined;
/**
* Remove the stored data in local storage essentially logging the user out.
*/
remove(): void;
}
/**
* Information about the temporary access code settings.
*/
export declare type TempAccessCodeChallenge = {
/**
* An optional admin contact value (like an admin email address or phone number) to be displayed in the admin contact message.
*/
adminContact?: string;
/**
* Indicates if the admin contact message should be displayed for this challenge.
*/
enableAdminContact?: boolean;
};
/**
* The configurable options for the `login` and `requestChallenge` methods.
*/
export declare interface TokenOptions {
/**
* The audience to be used for requesting API access. This defaults to the `globalAudience` set in your `IdaasClientOptions` if not set.
* Per OIDC spec, this parameter is optional and will be omitted from the authorization request if not provided.
*/
audience?: string;
/**
* The scope to be used on this authentication request.
*
* This defaults to the `globalScope` in your `IdaasClientOptions` if not set. If you are setting extra scopes and require `profile` and `email` to be included then you must include them in the provided scope.
*
* Note: By default, the `openid` scope is automatically included so you receive an ID token. Only set `includeOpenidScope` to `false` if you want to omit the `openid` scope and perform OAuth authorization without an ID token.
*/
scope?: string;
/**
* Determines whether the token obtained from this login request can use refresh tokens. This defaults to the `useRefreshToken` set in your `IdaasClientOptions` if not set.
*
* Note: Use of refresh tokens must be enabled on your IDaaS client application.
*/
useRefreshToken?: boolean;
/**
* Specifies the maximum age of a token in seconds.
* When tokens are refreshed using a refresh token, the original authentication time is preserved and this maxAge value continues to apply to that original authentication timestamp, not the refresh time.
*/
maxAge?: number;
/**
* Space-delimited ACR values used to determine the strength/quality of the method used to authenticate the user.
* Example: `"knowledge possession"`
*/
acrValues?: string;
/**
* Controls whether the `openid` scope is automatically added to the authorization request.
*
* When `true` (default), the `openid` scope is added and the flow expects an ID token. When `false`, the SDK omits
* automatic `openid` appending and does not require an ID token.
*
* @default true
*/
in