@azure/msal-browser
Version:
Microsoft Authentication Library for js
891 lines (888 loc) • 46 kB
JavaScript
/*! @azure/msal-browser v5.30.0 2026-11-18 */
'use strict';
import { InteractionClientBaseV2 } from './InteractionClientBaseV2.mjs';
import { createFlowMethodSelectionRequiredResultV2, FLOW_CODE_REQUIRED_V2, createFlowCodeRequiredResultV2, createFlowPasswordRequiredResultV2, createFlowSignInContinuationRequiredResultV2, createFlowNewPasswordRequiredResultV2, createFlowMFARequiredResultV2, createFlowCompletedResultV2, createFlowSignUpPasswordRequiredResultV2, createFlowAttributesRequiredResultV2, createFlowAuthMethodRegistrationRequiredResultV2, createFlowAuthMethodVerificationRequiredResultV2, createFlowExistingAccountCodeRequiredResultV2, FLOW_PASSWORD_REQUIRED_V2, createFlowExistingAccountPasswordRequiredResultV2 } from './result/FlowActionResultV2.mjs';
import { CustomAuthError } from '../../error/CustomAuthError.mjs';
import { SIGN_IN_UNSUPPORTED, SIGN_UP_UNSUPPORTED, UNSUPPORTED_FLOW_TRANSITION, RESET_PASSWORD_UNSUPPORTED, RESET_PASSWORD_TIMEOUT, UNSUPPORTED_FLOW_STEP, CONTINUATION_LINK_MISSING } from '../../network_client/custom_auth_api/v2/ErrorCodesV2.mjs';
import { CustomAuthFlowScenarioV2 } from '../../auth_flow/v2/CustomAuthFlowScenarioV2.mjs';
import { SIGN_IN_V2_START, SIGN_UP_V2_START, RESET_PASSWORD_V2_START, JIT_V2_ENROLL_AUTH_METHOD, JIT_V2_SUBMIT_CHALLENGE, JIT_V2_RESEND_CHALLENGE } from '../../telemetry/PublicApiId.mjs';
import { getPublicApiIdV2 } from '../../telemetry/FlowApiIdHelperV2.mjs';
import { AuthenticationFactorV2 } from '../../network_client/custom_auth_api/v2/result/BaseResultsV2.mjs';
import { VERIFY_RELATION, AuthenticationMethodTypeV2, ResponseStateV2, UPDATE_RELATION, POLL_RELATION, ENROLL_RELATION, CHALLENGE_RELATION, COLLECT_ATTRIBUTES_RELATION, PhoneRegistrationChannelV2, RISK_VERIFY_RELATION } from '../../network_client/custom_auth_api/v2/ApiClientConstantsV2.mjs';
import { SignUpSubmitAttributesNextActionV2 } from '../../network_client/custom_auth_api/v2/result/SignUpResultsV2.mjs';
import { InvalidArgumentError } from '../../error/InvalidArgumentError.mjs';
import { filterReservedSignUpAttributesV2 } from '../../utils/ArgumentValidator.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const POLL_MAX_ATTEMPTS = 5;
// TODO: Replace this fallback with the server-provided polling interval once available.
const POLL_INTERVAL_MS = 1500;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/*
* Drives server-directed Native Auth V2 flows.
*/
class FlowInteractionClientV2 extends InteractionClientBaseV2 {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthAuthority, apiClient) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthAuthority);
this.apiClient = apiClient;
}
/*
* Starts native auth V2 sign-in.
*/
async signIn(parameters) {
const correlationId = parameters.correlationId;
const context = this.createRequestContext(SIGN_IN_V2_START, correlationId);
this.logger.verbose("1jeyrn", correlationId);
const scopes = this.getScopes(parameters.scopes);
const entryResult = await this.apiClient.authorizeChallengeStart(context, scopes, parameters.claims);
const startResult = await this.apiClient.signInStart(this.requireLink(correlationId, entryResult.signInHref, {
code: SIGN_IN_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a sign-in link.",
}), {
continuationToken: entryResult.continuationToken,
username: parameters.username,
}, context);
this.ensureAuthenticationFactor(startResult.authenticationFactor, AuthenticationFactorV2.SINGLE_FACTOR, "sign-in start", correlationId);
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.SignIn,
scopes,
links: {},
};
const methods = startResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
}));
const supportedMethods = this.getSupportedSignInMethods(methods, correlationId);
if (supportedMethods.length > 1) {
return createFlowMethodSelectionRequiredResultV2({
correlationId,
continuationState,
methods: supportedMethods,
});
}
const selectedMethod = supportedMethods[0];
const challengeResult = await this.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
...continuationState.links,
challenge: selectedMethod.challengeHref,
},
},
});
if (challengeResult.type === FLOW_CODE_REQUIRED_V2) {
return {
...challengeResult,
method: selectedMethod,
};
}
return challengeResult;
}
/*
* Starts native auth V2 sign-up.
*/
async signUp(parameters) {
const correlationId = parameters.correlationId;
const pendingProfileAttributes = filterReservedSignUpAttributesV2(parameters.attributes, this.logger, correlationId);
const context = this.createRequestContext(SIGN_UP_V2_START, correlationId);
this.logger.verbose("19e1ak", correlationId);
const scopes = this.getScopes(parameters.scopes);
const entryResult = await this.apiClient.authorizeChallengeStart(context, scopes, parameters.claims);
const startResult = await this.apiClient.signUpStart(this.requireLink(correlationId, entryResult.signUpHref, {
code: SIGN_UP_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a sign-up link.",
}), {
continuationToken: entryResult.continuationToken,
username: parameters.username,
}, context);
if (startResult.nextAction === VERIFY_RELATION) {
if (startResult.type?.toLowerCase() !==
AuthenticationMethodTypeV2.EMAIL) {
const message = "New-account sign-up requires an email code challenge.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
return createFlowCodeRequiredResultV2({
correlationId,
continuationState: {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.SignUp,
scopes,
links: {
verify: startResult.verifyHref,
resend: startResult.resendHref,
},
signUp: {
purpose: "newAccount",
pendingProfileAttributes,
submittedAttributeIds: [],
},
},
channel: startResult.type,
sentTo: startResult.hint,
codeLength: startResult.codeLength,
});
}
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.SignUp,
scopes,
links: {},
signUp: {
purpose: "existingAccount",
},
};
this.ensureAuthenticationFactor(startResult.authenticationFactor, AuthenticationFactorV2.SINGLE_FACTOR, "existing-account sign-up", correlationId);
const supportedMethods = startResult.methods
.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
}))
.filter((method) => {
const methodType = method.type.toLowerCase();
return (methodType === AuthenticationMethodTypeV2.EMAIL ||
methodType === AuthenticationMethodTypeV2.PASSWORD);
});
if (supportedMethods.length === 0) {
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, "The existing-account sign-up response must include an email or password method.", correlationId);
}
if (supportedMethods.length > 1) {
return createFlowMethodSelectionRequiredResultV2({
correlationId,
continuationState,
methods: supportedMethods,
});
}
const selectedMethod = supportedMethods[0];
const challengeResult = await this.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
challenge: selectedMethod.challengeHref,
},
},
});
return this.toExistingAccountChallengeResult(challengeResult, selectedMethod, correlationId);
}
/*
* Starts native auth V2 password reset.
*/
async resetPassword(parameters) {
const correlationId = parameters.correlationId;
const context = this.createRequestContext(RESET_PASSWORD_V2_START, correlationId);
this.logger.verbose("1en88i", correlationId);
const scopes = this.getScopes(parameters.scopes);
const entryResult = await this.apiClient.authorizeChallengeStart(context, scopes, parameters.claims);
const startResult = await this.apiClient.resetPasswordStart(this.requireLink(correlationId, entryResult.resetPasswordHref, {
code: RESET_PASSWORD_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a reset-password link.",
}), {
username: parameters.username,
continuationToken: entryResult.continuationToken,
}, context);
this.ensureAuthenticationFactor(startResult.authenticationFactor, AuthenticationFactorV2.SINGLE_FACTOR, "password-reset start", correlationId);
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.PasswordReset,
scopes,
links: {},
};
const methods = startResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
}));
if (methods.length === 0) {
const message = "The password-reset start response did not include an authentication method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
if (methods.length > 1) {
this.logger.verbose("0k8yah", correlationId);
return createFlowMethodSelectionRequiredResultV2({
correlationId,
continuationState,
methods,
});
}
const selectedMethod = methods[0];
const challengeResult = await this.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
challenge: selectedMethod.challengeHref,
},
},
});
if (challengeResult.type === FLOW_CODE_REQUIRED_V2 &&
(challengeResult.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.EMAIL ||
challengeResult.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.SMS)) {
return {
...challengeResult,
method: selectedMethod,
};
}
const channel = challengeResult.type === FLOW_CODE_REQUIRED_V2
? challengeResult.channel
: AuthenticationMethodTypeV2.PASSWORD;
const message = `Challenge type '${challengeResult.type}' with channel '${channel}' is not supported for password reset.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
/*
* Requests a challenge for the selected authentication method.
*/
async requestChallenge(parameters) {
const challengeResult = await this.sendMethodChallenge(parameters, "requestChallenge");
const challengeType = challengeResult.type;
const normalizedChallengeType = challengeType?.toLowerCase();
const continuationState = this.createChallengeContinuationState(parameters.continuationState, challengeResult);
if (normalizedChallengeType === AuthenticationMethodTypeV2.PASSWORD) {
return createFlowPasswordRequiredResultV2({
correlationId: parameters.correlationId,
continuationState,
});
}
if (normalizedChallengeType === AuthenticationMethodTypeV2.EMAIL ||
normalizedChallengeType === AuthenticationMethodTypeV2.SMS) {
return createFlowCodeRequiredResultV2({
correlationId: parameters.correlationId,
continuationState,
channel: challengeType,
sentTo: challengeResult.hint,
codeLength: challengeResult.codeLength,
});
}
const message = challengeType
? `Challenge type '${challengeType}' is not supported.`
: "Challenge type is missing.";
this.logger.error(message, parameters.correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, parameters.correlationId);
}
/*
* Registers the selected authentication method.
*/
async registerAuthMethod(parameters) {
const { continuationState, correlationId } = parameters;
if (!parameters.verificationContact?.trim()) {
throw new InvalidArgumentError("verificationContact", correlationId);
}
const registrationRequest = this.createRegistrationRequest(parameters.method, parameters.verificationContact, continuationState.continuationToken, correlationId);
const context = this.createRequestContext(JIT_V2_ENROLL_AUTH_METHOD, correlationId);
this.logger.verbose("0dfkz9", correlationId);
const result = await this.apiClient.enrollAuthMethod(this.requireLink(correlationId, parameters.method.enrollHref), registrationRequest, context);
return this.createAuthMethodVerificationRequiredResult(continuationState, result, correlationId);
}
/*
* Activates the registered authentication method.
*/
async verifyAuthMethodRegistration(parameters) {
const { continuationState, correlationId } = parameters;
const context = this.createRequestContext(JIT_V2_SUBMIT_CHALLENGE, correlationId);
this.logger.verbose("073pof", correlationId);
const result = await this.apiClient.activateAuthMethod(this.requireLink(correlationId, continuationState.links.activate), {
continuationToken: continuationState.continuationToken,
otp: parameters.code,
}, context);
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp ||
continuationState.scenario ===
CustomAuthFlowScenarioV2.PasswordReset) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: result.continuationToken,
links: {},
},
});
}
return this.completeSignInAfterVerification(continuationState, result.continuationToken, correlationId);
}
/*
* Requests a replacement authentication-method activation challenge.
*/
async resendAuthMethodRegistrationChallenge(parameters) {
const { continuationState, correlationId } = parameters;
const context = this.createRequestContext(JIT_V2_RESEND_CHALLENGE, correlationId);
this.logger.verbose("04qvjc", correlationId);
const result = await this.apiClient.resendAuthMethodRegistrationChallenge(this.requireLink(correlationId, continuationState.links.resend), {
continuationToken: continuationState.continuationToken,
}, context);
return this.createAuthMethodVerificationRequiredResult(continuationState, result, correlationId);
}
/*
* Verifies the submitted one-time code.
*/
async submitCode(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitCode", correlationId, parameters.authenticationFactor), correlationId);
this.logger.verbose("16ks6n", correlationId);
const verifyHref = this.requireLink(correlationId, continuationState.links.verify);
const verifyRequest = {
continuationToken: continuationState.continuationToken,
otp: parameters.code,
};
const verifyResult = await this.apiClient.verifyChallenge(verifyHref, verifyRequest, context);
if (continuationState.scenario ===
CustomAuthFlowScenarioV2.PasswordReset &&
parameters.authenticationFactor ===
AuthenticationFactorV2.MULTI_FACTOR &&
verifyResult.nextAction === ResponseStateV2.CONTINUE) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {},
},
});
}
if (continuationState.scenario ===
CustomAuthFlowScenarioV2.PasswordReset &&
parameters.authenticationFactor !==
AuthenticationFactorV2.MULTI_FACTOR &&
verifyResult.nextAction === UPDATE_RELATION) {
return createFlowNewPasswordRequiredResultV2({
correlationId,
continuationState: {
continuationToken: verifyResult.continuationToken,
scenario: continuationState.scenario,
scopes: continuationState.scopes,
links: { update: verifyResult.updateHref },
},
});
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignIn) {
return this.handleSignInVerification(continuationState, verifyResult, correlationId);
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp &&
continuationState.signUp?.purpose === "existingAccount") {
return this.handleSignInVerification(continuationState, verifyResult, correlationId);
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp) {
return this.handleSignUpVerification(continuationState, verifyResult, correlationId);
}
const message = `Verification next action '${verifyResult.nextAction}' is not supported for the '${continuationState.scenario}' flow.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
/*
* Requests a replacement one-time code.
*/
async resendCode(parameters) {
const challengeResult = await this.sendMethodChallenge(parameters, "resendCode");
const challengeType = challengeResult.type?.toLowerCase();
if (challengeType !== AuthenticationMethodTypeV2.EMAIL &&
challengeType !== AuthenticationMethodTypeV2.SMS) {
const message = "A replacement code requires an email or SMS code challenge.";
this.logger.error(message, parameters.correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, parameters.correlationId);
}
return createFlowCodeRequiredResultV2({
correlationId: parameters.correlationId,
continuationState: this.createChallengeContinuationState(parameters.continuationState, challengeResult),
channel: challengeResult.type,
sentTo: challengeResult.hint,
codeLength: challengeResult.codeLength,
});
}
async submitSignUpAttributes(parameters) {
const { continuationState, correlationId, attributes: submittedAttributes, } = parameters;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitAttributes", correlationId), correlationId);
this.logger.verbose("0js2ub", correlationId);
const submittedAttributeIds = Object.keys(submittedAttributes);
const submitResult = await this.apiClient.submitSignUpAttributes(this.requireLink(correlationId, continuationState.links.submitAttributes), {
continuationToken: continuationState.continuationToken,
attributes: submittedAttributes,
}, context);
return this.toSignUpSubmitAttributesResult(submitResult, {
...continuationState,
signUp: {
purpose: "newAccount",
submittedAttributeIds: [
...new Set([
...(continuationState.signUp
?.submittedAttributeIds ?? []),
...submittedAttributeIds,
]),
],
},
}, correlationId);
}
/*
* Submits the new password and polls for the next action: method registration,
* MFA, or a continuation for explicit sign-in.
*/
async submitNewPassword(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitNewPassword", correlationId), correlationId);
this.logger.verbose("0ie1qa", correlationId);
const updateResult = await this.apiClient.submitNewPassword(this.requireLink(correlationId, continuationState.links.update), {
continuationToken: continuationState.continuationToken,
newPassword: parameters.newPassword,
}, context);
let pollToken = updateResult.continuationToken;
let pollHref = updateResult.pollHref;
let pollResult;
let isPolling = false;
for (let attempt = 1; attempt <= POLL_MAX_ATTEMPTS; attempt++) {
pollResult = await this.apiClient.poll(pollHref, { continuationToken: pollToken }, context);
isPolling = pollResult.nextAction === POLL_RELATION;
if (pollResult.nextAction !== POLL_RELATION) {
break;
}
pollToken = pollResult.continuationToken;
pollHref = this.requireLink(correlationId, pollResult.pollHref);
if (attempt < POLL_MAX_ATTEMPTS) {
await delay(POLL_INTERVAL_MS);
}
}
if (!pollResult || isPolling) {
const message = "The password reset did not complete within the allotted number of polling attempts.";
this.logger.error(message, correlationId);
throw new CustomAuthError(RESET_PASSWORD_TIMEOUT, message, correlationId);
}
if (pollResult.nextAction === ENROLL_RELATION && pollResult.methods) {
return this.createAuthMethodRegistrationRequiredResult({
correlationId,
continuationState: {
...continuationState,
continuationToken: pollResult.continuationToken,
links: {},
},
methods: pollResult.methods,
});
}
if (pollResult.nextAction === CHALLENGE_RELATION) {
if (!pollResult.authenticationFactor) {
const message = "Password-reset MFA challenge is missing its authentication factor.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
this.ensureAuthenticationFactor(pollResult.authenticationFactor, AuthenticationFactorV2.MULTI_FACTOR, "after password reset", correlationId);
return createFlowMFARequiredResultV2({
correlationId,
continuationState: {
continuationToken: pollResult.continuationToken,
scenario: continuationState.scenario,
scopes: continuationState.scopes,
links: {},
},
methods: pollResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
})),
});
}
if (pollResult.nextAction === ResponseStateV2.CONTINUE) {
this.logger.verbose("0hrwdj", correlationId);
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
continuationToken: pollResult.continuationToken,
scenario: continuationState.scenario,
scopes: continuationState.scopes,
links: {},
},
});
}
const message = `Password reset poll next action '${pollResult.nextAction}' is not supported.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
/*
* Verifies the sign-in password.
*/
async submitSignInPassword(parameters) {
const verifyResult = await this.verifySignInPassword(parameters);
return this.handleSignInVerification(parameters.continuationState, verifyResult, parameters.correlationId);
}
/*
* Signs the user in from a completed flow.
*/
async signInWithContinuation(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const apiId = this.resolveStepApiId(continuationState.scenario, "signInWithContinuation", correlationId);
const context = this.createRequestContext(apiId, correlationId);
this.logger.verbose("09mk3f", correlationId);
const tokenResponse = await this.apiClient.completeWithTokens({
continuationToken: continuationState.continuationToken,
}, context);
const authenticationResult = await this.handleTokenResponse(tokenResponse, continuationState.scopes, correlationId, apiId);
this.logger.verbose("15nu4j", correlationId);
return createFlowCompletedResultV2({
correlationId,
authenticationResult,
});
}
async handleSignInVerification(continuationState, verifyResult, correlationId) {
if (verifyResult.nextAction === ENROLL_RELATION) {
return this.createAuthMethodRegistrationRequiredResult({
correlationId,
continuationState: {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {},
},
methods: verifyResult.methods,
});
}
if (verifyResult.nextAction === CHALLENGE_RELATION) {
this.ensureAuthenticationFactor(verifyResult.authenticationFactor, AuthenticationFactorV2.MULTI_FACTOR, "after authentication verification", correlationId);
return createFlowMFARequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {},
},
methods: verifyResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
})),
});
}
if (verifyResult.nextAction === ResponseStateV2.CONTINUE) {
return this.completeSignInAfterVerification(continuationState, verifyResult.continuationToken, correlationId);
}
const message = `Verification next action '${verifyResult.nextAction}' is not supported for authentication.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
async handleSignUpVerification(continuationState, verifyResult, correlationId) {
if (verifyResult.nextAction === COLLECT_ATTRIBUTES_RELATION) {
const requestedAttributes = verifyResult.attributes;
const requestedPasswordAttribute = requestedAttributes.find((attribute) => attribute.attributeId.toLowerCase() === "password");
const nextContinuationState = {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {
submitAttributes: verifyResult.submitAttributesHref,
},
};
const pendingProfileAttributes = continuationState.signUp?.pendingProfileAttributes;
if (pendingProfileAttributes &&
Object.keys(pendingProfileAttributes).length > 0) {
return this.submitSignUpAttributes({
correlationId,
continuationState: nextContinuationState,
attributes: pendingProfileAttributes,
});
}
if (requestedPasswordAttribute) {
return createFlowSignUpPasswordRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
requestedPasswordAttribute,
});
}
return createFlowAttributesRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes: requestedAttributes,
});
}
if (verifyResult.nextAction === ENROLL_RELATION) {
return this.createAuthMethodRegistrationRequiredResult({
correlationId,
continuationState: {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {},
},
methods: verifyResult.methods,
});
}
if (verifyResult.nextAction === ResponseStateV2.CONTINUE) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: verifyResult.continuationToken,
links: {},
},
});
}
const message = `Verification next action '${verifyResult.nextAction}' is not supported for the '${continuationState.scenario}' flow.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
getSupportedSignInMethods(methods, correlationId) {
const supportedMethods = methods.filter((method) => {
const methodType = method.type.toLowerCase();
return (methodType === AuthenticationMethodTypeV2.EMAIL ||
methodType === AuthenticationMethodTypeV2.PASSWORD ||
methodType === AuthenticationMethodTypeV2.SMS);
});
if (supportedMethods.length > 0) {
return supportedMethods;
}
const message = "The sign-in start response did not include a supported email, SMS, or password method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
createRegistrationRequest(method, verificationContact, continuationToken, correlationId) {
if (method.type === AuthenticationMethodTypeV2.EMAIL) {
return {
continuationToken,
email: verificationContact,
};
}
const [channel] = method.channels ?? [];
if (method.type === AuthenticationMethodTypeV2.PHONE &&
channel === PhoneRegistrationChannelV2.SMS) {
return {
continuationToken,
phoneNumber: verificationContact,
channel,
};
}
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, "The selected authentication method is not supported for registration.", correlationId);
}
createAuthMethodRegistrationRequiredResult(parameters) {
const { correlationId, continuationState } = parameters;
const supportedMethods = parameters.methods.filter((method) => {
const methodType = method.type.trim().toLowerCase();
return (methodType === AuthenticationMethodTypeV2.EMAIL ||
(methodType === AuthenticationMethodTypeV2.PHONE &&
method.channels?.includes(PhoneRegistrationChannelV2.SMS)));
});
if (supportedMethods.length === 0) {
const message = "The enrollment response did not include a supported registration method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
const methods = supportedMethods.map((method) => {
const methodType = method.type.trim().toLowerCase();
const channel = method.channels?.find((candidate) => candidate === PhoneRegistrationChannelV2.SMS);
if (methodType === AuthenticationMethodTypeV2.EMAIL) {
return {
type: AuthenticationMethodTypeV2.EMAIL,
enrollHref: this.requireLink(correlationId, method.enrollHref),
};
}
if (methodType === AuthenticationMethodTypeV2.PHONE &&
channel === PhoneRegistrationChannelV2.SMS) {
return {
type: AuthenticationMethodTypeV2.PHONE,
channels: [channel],
enrollHref: this.requireLink(correlationId, method.enrollHref),
};
}
const message = "The enrollment response included an unsupported registration method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
});
return createFlowAuthMethodRegistrationRequiredResultV2({
correlationId,
continuationState,
methods,
});
}
createAuthMethodVerificationRequiredResult(continuationState, result, correlationId) {
return createFlowAuthMethodVerificationRequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: result.continuationToken,
links: {
activate: this.requireLink(correlationId, result.activateHref),
resend: result.resendHref,
},
},
sentTo: result.hint,
codeLength: result.codeLength,
});
}
toSignUpSubmitAttributesResult(result, continuationState, correlationId) {
const nextAction = result.nextAction;
if (result.nextAction === SignUpSubmitAttributesNextActionV2.ENROLL) {
return this.createAuthMethodRegistrationRequiredResult({
correlationId,
continuationState: {
...continuationState,
continuationToken: result.continuationToken,
links: {},
},
methods: result.methods,
});
}
if (result.nextAction ===
SignUpSubmitAttributesNextActionV2.COLLECT_ATTRIBUTES) {
const requestedAttributes = result.attributes;
this.ensureValidSignUpAttributeCollectionAfterSubmission(requestedAttributes, continuationState, correlationId);
const nextContinuationState = {
...continuationState,
continuationToken: result.continuationToken,
links: {
submitAttributes: result.submitAttributesHref,
},
};
const requestedPasswordAttribute = requestedAttributes.find((attribute) => attribute.attributeId.toLowerCase() === "password");
if (requestedPasswordAttribute) {
return createFlowSignUpPasswordRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
requestedPasswordAttribute,
});
}
return createFlowAttributesRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes: requestedAttributes,
});
}
if (result.nextAction === SignUpSubmitAttributesNextActionV2.CONTINUE) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
...continuationState,
continuationToken: result.continuationToken,
links: {},
},
});
}
const message = `Sign-up attribute submission next action '${nextAction}' is not supported.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
ensureValidSignUpAttributeCollectionAfterSubmission(requestedAttributes, continuationState, correlationId) {
const submittedAttributeIds = continuationState.signUp?.submittedAttributeIds ?? [];
const hasSubmittedPassword = submittedAttributeIds.some((attributeId) => attributeId.toLowerCase() === "password");
const invalidAttribute = requestedAttributes.find((requestedAttribute) => requestedAttribute.attributeId.toLowerCase() === "password"
? hasSubmittedPassword
: submittedAttributeIds.includes(requestedAttribute.attributeId));
if (invalidAttribute) {
const message = invalidAttribute.attributeId.toLowerCase() === "password"
? "The sign-up API cannot request password collection after attribute submission."
: "The sign-up API requested an attribute that was already successfully submitted.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
}
ensureAuthenticationFactor(authenticationFactor, expectedFactor, transition, correlationId) {
if (authenticationFactor === expectedFactor) {
return;
}
const message = `Authentication factor '${authenticationFactor}' is not supported for ${transition}.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
toExistingAccountChallengeResult(challengeResult, method, correlationId) {
if (challengeResult.type === FLOW_CODE_REQUIRED_V2 &&
challengeResult.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.EMAIL) {
return createFlowExistingAccountCodeRequiredResultV2({
correlationId,
continuationState: challengeResult.continuationState,
method,
channel: challengeResult.channel,
sentTo: challengeResult.sentTo,
codeLength: challengeResult.codeLength,
});
}
if (challengeResult.type === FLOW_PASSWORD_REQUIRED_V2) {
return createFlowExistingAccountPasswordRequiredResultV2({
correlationId,
continuationState: challengeResult.continuationState,
});
}
const message = "Existing-account sign-up requires an email code challenge or a password challenge.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
async verifySignInPassword(parameters) {
const { continuationState, correlationId } = parameters;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitPassword", correlationId), correlationId);
this.logger.verbose("13uf3o", correlationId);
return this.apiClient.verifyChallenge(this.requireLink(correlationId, continuationState.links.verify), {
continuationToken: continuationState.continuationToken,
password: parameters.password,
}, context);
}
completeSignInAfterVerification(continuationState, continuationToken, correlationId) {
return this.signInWithContinuation({
correlationId,
continuationState: {
...continuationState,
continuationToken,
links: {},
},
});
}
async sendMethodChallenge(parameters, step) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const challengeHref = step === "resendCode"
? continuationState.links.resend
: continuationState.links.challenge;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, step, correlationId, parameters.authenticationFactor), correlationId);
this.logger.verbose(step === "0d2mys"
? "Resending V2 one-time code."
: "Requesting V2 challenge.", correlationId);
const challengeResult = await this.apiClient.requestChallenge(this.requireLink(correlationId, challengeHref), { continuationToken: continuationState.continuationToken }, context);
const nextAction = challengeResult.nextAction;
if (challengeResult.nextAction === VERIFY_RELATION) {
return challengeResult;
}
if (challengeResult.nextAction === RISK_VERIFY_RELATION) {
return this.apiClient.verifyRisk(challengeResult.riskVerifyHref, { continuationToken: challengeResult.continuationToken }, context);
}
const message = `Challenge next action '${nextAction}' is not supported.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
createChallengeContinuationState(continuationState, challengeResult) {
return {
...continuationState,
continuationToken: challengeResult.continuationToken,
links: {
challenge: continuationState.links.challenge,
verify: challengeResult.verifyHref,
resend: challengeResult.resendHref ??
continuationState.links.resend,
},
};
}
resolveStepApiId(scenario, step, correlationId, authenticationFactor) {
const apiId = getPublicApiIdV2(scenario, step, authenticationFactor);
if (apiId === undefined) {
const message = `No telemetry API id is registered for step '${step}' of the '${scenario}' flow.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_STEP, message, correlationId);
}
return apiId;
}
requireLink(correlationId, href, missingLinkError) {
if (typeof href !== "string" || !href.trim()) {
const errorCode = missingLinkError?.code ?? CONTINUATION_LINK_MISSING;
const message = missingLinkError?.message ??
"The continuation state is missing a link required to advance the flow.";
this.logger.error(message, correlationId);
throw new CustomAuthError(errorCode, message, correlationId);
}
return href;
}
}
export { FlowInteractionClientV2 };
//# sourceMappingURL=FlowInteractionClientV2.mjs.map