1
0
mirror of https://github.com/bitwarden/browser synced 2026-02-14 15:33:55 +00:00

feat(2FA-UI-Refresh): [Auth/PM-8113] - 2FA Components Consolidation and UI Refresh (#12087)

* PM-8113 - Deprecate TwoFactorComponentRefactor feature flag in favor of UnauthenticatedExtensionUIRefresh flag

* PM-8113 - Rename all existing 2FA components as V1.

* PM-8113 - TwoFactorAuthComp - Add comment explaining that tagged unused import is used a dialog.

* PM-8113 - 2FA Auth Comp - deprecate captcha

* PM-8113 - LoginStrategySvc - add todo for deprecation of captcha response

* PM-8113 - TwoFactorAuth tests - remove captcha

* PM-8113  - TwoFactorAuthComp HTML - remove captcha

* PM-8113  - Web Two Factor Auth - update deps

* PM-8113 - Move all new two-factor-auth components into libs/auth instead of libs/angular/src/auth

* PM-8113 - Add new child-components folder to help differentiate between top level page component and child components

* PM-8113 - Add todo for browser TwoFactorAuthEmailComponent

* PM-8113 - TwoFactorAuth - progress on consolidation

* PM-8113 - TwoFactorAuth - add TODO to ensure I don't miss web on success logic

* PM-8113 - TwoFactorAuth - Deprecate browser implementation of two-factor-auth and move all logic into single component - WIP

* PM-8113 - Bring across 2FA session timeout to new 2FA orchestrator comp

* PM-8113 - Export TwoFactorAuth from libs/auth

* PM-8113 - Fix 2FA Auth Comp tests by adding new service deps.

* PM-8113 - Fix TwoFactorAuthExpiredComp imports + TwoFactorAuthComponent imports on other clients.

* PM-8113 - 2FA Auth Comp - Progress on removing onSuccessfulLogin callback

* PM-8113 - 2FA Auth - update deps to private as inheritance will no longer be used.

* PM-8113 - TwoFactorAuthComp - Refactor init a bit.

* PM-8113  - TwoFactorAuthComp - More naming refactors

* PM-8113  - TwoFactorAuth - (1) more refactoring (2) removed onSuccessfulLoginNavigate (3) after successful login we always loginEmailService.clearValues()

* PM-8113 - TwoFactorAuthComp Tests - clean up tests for removed callbacks.

* PM-8113 - TwoFactorAuthComponent - refactor default success route handling

* PM-8113 - TwoFactorAuthComp - More refactoring

* PM-8113 - TwoFactorAuthComp - more refactors

* PM-8113 - TwoFactorAuth - Remove unused service dep

* PM-8113 - TwoFactorAuthComp - Refactor out unused button action text and move checks for continue button visibility into component

* PM-8113 - TwoFactorAuthComponent - Add type for providerData

* PM-8113 - TwoFactorAuthComponent - Add todo

* PM-8113 - TwoFactorAuthComponent - Add client type

* PM-8113 - TwoFactorAuth - implement browser specific SSO + 2FA logic

* PM-8113 - TwoFactorService Abstraction - refactor to use proper functions + mark methods as abstract properly + add null return to getProviders

* PM-8113 - Refactor 2FA Guard logic out of ngOnInit and into own tested guard. Updated all routes.

* PM-8113 - TwoFactorAuthComponent - WIP on webauthn init.

* PM-8113 - TwoFactorAuthComponent - pull webauthn fallback response handling into primary init with checks based on client for if it should be processed.

* PM-8113 - TwoFactorAuthComponent - move linux popup width extension logic into ExtensionTwoFactorAuthComponentService

* PM-8113 - WebTwoFactorAuthComponentService - add explicit override for web's determineLegacyKeyMigrationAction method.

* PM-8113 - Implement new TwoFactorAuthComponentService .openPopoutIfApprovedForEmail2fa to replace extension specific init logic.

* PM-8113 - TwoFactorAuthComponent - misc cleanup

* PM-8113 - TwoFactorAuthComponent - more clean up

* PM-8113 - TwoFactorAuthComponent - WIP on removing TDE callbacks

* PM-8113 - TwoFactorAuthComponent - finish refactoring out all callbacks

* PM-8113 - TwoFactorAuthComponent - remove now unused method

* PM-8113 - TwoFactorAuthComponent - refactor routes.

* PM-8113 - TwoFactorAuthComponent - add TODO

* PM-8113 - TwoFactorAuthComp - isTrustedDeviceEncEnabled - add undefined check for optional window close. + Add todo

* PM-8113 - TwoFactorAuthComponent tests - updated to pass

* PM-8113 - (1) Consolidate TwoFactorAuthEmail component into new service architecture (2) Move openPopoutIfApprovedForEmail2fa to new TwoFactorAuthEmailComponentService

* PM-8113 - Refactor libs/auth/2fa into barrel files.

* PM-8113 - Move TwoFactorAuthEmail content to own folder.

* PM-8113 - Move 2FA Duo to own comp folder.

* PM-8113 - ExtensionTwoFactorAuthEmailComponentService - Add comment

* PM-8113 - TwoFactorAuthEmailComponentService - add docs

* PM-8113  - TwoFactorAuthDuoComponentService - define top level abstraction and each clients implementation of the duo2faResultListener

* PM-8113 - TwoFactorAuthDuoCompService - add client specific handling for launchDuoFrameless

* PM-8113 - Delete no longer used client specific two factor auth duo components.

* PM-8113 - Register TwoFactorAuthDuoComponentService implementation in each client.

* PM-8113 - TwoFactorAuthComp - add destroy ref to fix warnings.

* PM-8113 - Remove accidentally checked in dev change

* PM-8113 - TwoFactorAuthComp - (1) Add loading state (2) Add missing  CheckboxModule import

* PM-8113 - TwoFactorAuthDuoComponent - update takeUntilDestroyed to pass in destroy context as you can't use takeUntilDestroyed in ngOnInit without it.

* PM-8113 - TwoFactorAuthWebAuthnComponent - remove no longer necessary webauthn new tab check as webauthn seems to work without it

* PM-8113 - TwoFactorAuthWebAuthnComp - refactor names and add todo

* PM-8113 - (1) Move WebAuthn 2FA comp to own folder (2) build out client service for new tab logic

* PM-8113 - Register TwoFactorAuthWebAuthnComponentServices

* PM-8113 - Tweak TwoFactorAuthWebAuthnComponentService and add to TwoFactorAuthWebAuthnComponent

* PM-8113 - WebTwoFactorAuthDuoComponentService - fix type issue

* PM-8113 - ExtensionTwoFactorAuthDuoComponentService - attempt to fix type issue.

* PM-8113 - Remove ts-strict-ignore

* PM-8113 - TwoFactorAuthWebAuthnComponent - satisfy strict typescript reqs.

* PM-8113 - TwoFactorAuthComponent - some progress on strict TS conversion

* PM-8113 - TwoFactorAuthComp - fixed all strict typescript issues.

* PM-8113 - TwoFactorAuthComp - remove no longer necessary webauthn code

* PM-8113 - ExtensionTwoFactorAuthComponentService - handleSso2faFlowSuccess - add more context

* PM-8113 - TwoFactorAuthComp - TDE should use same success handler method

* PM-8113 - Fix SSO + 2FA result handling by closing proper popout window

* PM-8113 - Add todo

* PM-8113 - Webauthn 2FA - As webauthn popout doesn't persist SSO state, have to genercize success logic (which should be a good thing but requires confirmation testing).

* PM-8113 - Per main changes, remove deprecated I18nPipe from 2fa comps that use it.

* PM-8113 - Remove more incorrect i18nPipes

* PM-8113 - TwoFactorAuth + Webauthn - Refactor logic

* PM-8113 - TwoFactorAuth - build submitting loading logic

* PM-8113 - TwoFactorAuth - remove loading as submitting.

* PM-8113 - TwoFactorAuth - update to latest authN session timeout logic

* PM-8113 - AuthPopoutWindow - Add new single action popout for email 2FA so we can close it programmatically

* PM-8113 - Update  ExtensionTwoFactorAuthComponentService to close email 2FA single action popouts.

* PM-8113 - Fix build after merge conflict issue

* PM-8113 - 2FA - Duo & Email comps - strict typescript adherence.

* PM-8113 - TwoFactorAuth - Clean up unused stuff and get tests passing

* PM-8113 - Clean up used service method + TODO as I've confirmed it works for other flows.

* PM-8113 - TODO: test all comp services

* PM-8113 - TwoFactorAuthComponent Tests - fix tests by removing mock of removed method.

* PM-8113 - Revert changes to login strategies to avoid scope creep for the sake of typescript strictness.

* PM-8113 - ExtensionTwoFactorAuthComponentService tests

* PM-8113 - Test ExtensionTwoFactorAuthDuoComponentService

* PM-8113 - ExtensionTwoFactorAuthEmailComponentService - add tests

* PM-8113 - Test ExtensionTwoFactorAuthWebAuthnComponentService

* PM-8113 - Add 2fa icons (icons need tweaking still)

* PM-8113 - TwoFactorAuthComponent - add setAnonLayoutDataByTwoFactorProviderType and handle email case as POC

* PM-8113 - TwoFactorEmailComp - work on converting to new design

* PM-8113 - Update icons with proper svg with scaling via viewbox

* PM-8113 - Update icons to use proper classes

* PM-8113 - 2FA Auth Comp - Progress on implementing design changes

* PM-8113 - TwoFactorOptionsComponent - add todos

* PM-8113 - 2fa Email Comp - add style changes per discussion with design

* PM-8113 - TwoFactorAuthComponent - use2faRecoveryCode - build out method per discussion with design

* PM-8113 - TwoFactorAuthComp - fix comp tests

* PM-8113 - TwoFactorAuthComp - progress on adding 2fa provider page icons and subtitles

* PM-8113 - Browser Translations - update duoTwoFactorRequiredPageSubtitle to match design discussion

* PM-8113 - TwoFactorAuthComp - more work on getting page title / icons working

* PM-8113 - Add todo

* PM-8113 - TwoFactorAuthDuoComponent Html - remove text that was moved to page subtitle.

* PM-8113 - 2FA Auth Comp - Duo icon works

* PM-8113 - (1) Add Yubico logo icon (2) Rename Yubikey icon to security key icon

* PM-8113 - TwoFactorAuthComp - remove icon from launch duo button per figma

* PM-8113 - Mark old two-factor-options component as v1.

* PM-8113 - Web - TwoFactorOptionsComponentV1 - Fix import

* PM-8113 - Fix more imports

* PM-8113 - Adjust translations based on meeting with Design

* PM-8113 - TwoFactorOptionsComponent - deprecate recovery code functionality

* PM-8113 - TwoFactorOptionsComponent - remove icon disable logic and unused imports

* PM-8113 - 2FA Options Comp rewritten to match figma

* PM-8113 - TwoFactorOptions - (1) Sort providers like setup screen (2) Add responsive scaling

* PM-8113 - Webauthn 2FA - WIP on updating connectors to latest style

* PM-8113 - Webauthn connector - clean up commented out code and restore block style

* PM-8113 - TwoFactorAuthWebAuthn - Add loading state for iframe until webauthn ready

* PM-8113 - Webauthn Iframe - update translation per figma

* PM-8113 - TwoFactorAuthComp - per figma, put webauthn after checkbox.

* PM-8113 - WebAuthn Fallback connector - UI refreshed

* PM-8113 - Two Factor Options - Implement wrapping

* PM-8113 - TwoFactorAuthAuthenticator - Remove text per figma

* PM-8113 - TwoFactorAuthYubikey - Clean up design per figma

* PM-8113 - Refactor all 2FA flows to use either reactive forms or programmatic submission so we get the benefit of onSubmit form validation like we have elsewhere.

* PM-8113 - 2FA Auth Comp - for form validated 2FA methods, add enter support.

* PM-8113 - TwoFactorAuthComp - Add loginSuccessHandlerService

* PM-8113 - DesktopTwoFactorAuthDuoComponentService - add tests

* PM-8113 - WebTwoFactorAuthDuoComponentService test file - WIP on tests

* PM-8113 - WebTwoFactorAuthDuoComponentService - test listenForDuo2faResult

* PM-8113 - TwoFactorAuthComp - (1) remove unused deps (2) get tests passing

* PM-8113 - Add required to inputs

* PM-8113 - TwoFactorAuth - Save off 2FA providers map so we can only show the select another 2FA method if the user actually has more than 1 configured 2FA method.

* PM-8113 - Webauthn iframe styling must be adjusted per client so adjust desktop and browser extension

* PM-8113 - TwoFactorAuthComp - Integrate latest ssoLoginService changes

* PM-8113 - Desktop & Browser routing modules - add new page title per figma

* PM-8113 - WebAuthn - added optional awaiting security key interaction button state to improve UX.

* PM-8113 - TwoFactorAuthComp - refactor to avoid reactive race condition with retrieval of active user id.

* PM-8113 - ExtensionTwoFactorAuthEmailComponentService - force close the popup since it has stopped closing when the popup opens.

* PM-8113 - TwoFactorAuth - refactor enter key press to exempt non-applicable flows from enter key handling

* PM-8113 - Refactor ExtensionTwoFactorAuthComponentService methods to solve issues with submission

* PM-8113 - TwoFactorAuth - fix programmatic submit of form

* PM-8113 - Fix ExtensionTwoFactorAuthComponentService tests

* PM-8113 - Extension - Webauthn iframe - remove -10px margin

* PM-8113 - Extension Routing module - 2FA screens need back button

* PM-8113 - Get Duo working in extension

* PM-8113 - TwoFactorOptions - tweak styling of row styling to better work for extension

* PM-8113 - TwoFactorWebauthnComp - new tab button styling per figma

* PM-8113 - 2FA Comp - Update logic for hiding / showing the remember me checkbox

* PM-8113 - TwoFactorAuthWebAuthnComp - new tab flow - fix remember me

* PM-8113 - Per PR feedback, add TODO for better provider and module structure for auth component client logic services.

* PM-8113 - TwoFactorAuth - add missing TDE offboarding logic.

* PM-8113 - TwoFactorAuthComponent tests - fix tests

* PM-8113 - 2FA Auth Comp HTML - per PR feedback, remove unnecessary margin bottom

* PM-8113 - 2FA Comp - per PR feedback, remove inSsoFlow as it isn't used.

* PM-8113 - TwoFactorOptionsComp - Clean up no longer needed emitters.

* PM-8113 - TwoFactorOptions - per PR feedback, clean up any usage

* PM-8113 - TwoFactorAuthComp - per PR feedback, rename method from selectOtherTwofactorMethod to selectOtherTwoFactorMethod

* PM-8113 - Per PR feedback, fix translations misspelling

* PM-8113 - TwoFactorAuthSecurityKeyIcon - fix hardcoded value

* PM-8113 - TwoFactorAuthSecurityKeyIcon - fix extra "

* PM-8113 - TwoFactorAuthDuo - Per PR feedback, remove empty template.

* PM-8113 - LooseComponentsModule - re-add accidentally removed component

* PM-8113 - TwoFactorAuthWebAuthnIcon - per PR feedback, fix hardcoded stroke value.

* PM-8113 - Desktop AppRoutingModule - per PR feedback, remove unnecessary AnonLayoutWrapperComponent component property.

* PM-8113 - Update apps/browser/src/auth/services/extension-two-factor-auth-duo-component.service.spec.ts to fix misspelling

Co-authored-by: rr-bw <102181210+rr-bw@users.noreply.github.com>

* PM-8113 - TwoFactorAuthComp - Per PR feedback, add trim to token value

* PM-8113 - TwoFactorService - add typescript strict

* PM-8113 - TwoFactorService - per PR feedback, add jsdocs

* PM-8113 - Per PR feedback, fix misspelling

* PM-8113 - Webauthn fallback - per PR feedback fix stroke

* PM-8113 - Update apps/web/src/connectors/webauthn-fallback.html

Co-authored-by: rr-bw <102181210+rr-bw@users.noreply.github.com>

* PM-8113 - Update libs/auth/src/angular/icons/two-factor-auth/two-factor-auth-webauthn.icon.ts

Co-authored-by: rr-bw <102181210+rr-bw@users.noreply.github.com>

---------

Co-authored-by: rr-bw <102181210+rr-bw@users.noreply.github.com>
This commit is contained in:
Jared Snider
2025-02-24 09:59:14 -05:00
committed by GitHub
parent 886cf48e77
commit acbff6953c
112 changed files with 3225 additions and 1925 deletions

View File

@@ -0,0 +1,3 @@
export * from "./two-factor-auth-email";
export * from "./two-factor-auth-duo";
export * from "./two-factor-auth-webauthn";

View File

@@ -0,0 +1,6 @@
<ng-container>
<bit-form-field>
<bit-label>{{ "verificationCode" | i18n }}</bit-label>
<input bitInput type="text" appAutofocus appInputVerbatim [formControl]="tokenFormControl" />
</bit-form-field>
</ng-container>

View File

@@ -0,0 +1,35 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, Input } from "@angular/core";
import { ReactiveFormsModule, FormsModule, FormControl } from "@angular/forms";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import {
ButtonModule,
LinkModule,
TypographyModule,
FormFieldModule,
AsyncActionsModule,
} from "@bitwarden/components";
@Component({
standalone: true,
selector: "app-two-factor-auth-authenticator",
templateUrl: "two-factor-auth-authenticator.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
providers: [],
})
export class TwoFactorAuthAuthenticatorComponent {
@Input({ required: true }) tokenFormControl: FormControl | undefined = undefined;
}

View File

@@ -0,0 +1 @@
export * from "./two-factor-auth-duo-component.service";

View File

@@ -0,0 +1,32 @@
import { Observable } from "rxjs";
export interface Duo2faResult {
code: string;
state: string;
/**
* The code and the state joined by a | character.
*/
token: string;
}
/**
* A service which manages all the cross client logic for the duo 2FA component.
*/
export abstract class TwoFactorAuthDuoComponentService {
/**
* Retrieves the result of the duo two-factor authentication process.
* @returns {Observable<Duo2faResult>} An observable that emits the result of the duo two-factor authentication process.
*/
abstract listenForDuo2faResult$(): Observable<Duo2faResult>;
/**
* Launches the client specific duo frameless 2FA flow.
*/
abstract launchDuoFrameless(duoFramelessUrl: string): Promise<void>;
/**
* Optionally launches the extension duo 2FA single action popout
* Only applies to the extension today.
*/
abstract openTwoFactorAuthDuoPopout?(): Promise<void>;
}

View File

@@ -0,0 +1,96 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, DestroyRef, EventEmitter, Input, OnInit, Output } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import {
ButtonModule,
LinkModule,
TypographyModule,
FormFieldModule,
AsyncActionsModule,
ToastService,
} from "@bitwarden/components";
import { DuoLaunchAction } from "../../two-factor-auth-component.service";
import {
Duo2faResult,
TwoFactorAuthDuoComponentService,
} from "./two-factor-auth-duo-component.service";
@Component({
standalone: true,
selector: "app-two-factor-auth-duo",
template: "",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
providers: [],
})
export class TwoFactorAuthDuoComponent implements OnInit {
@Output() tokenEmitter = new EventEmitter<string>();
@Input() providerData: any;
duoFramelessUrl: string | undefined = undefined;
constructor(
protected i18nService: I18nService,
protected platformUtilsService: PlatformUtilsService,
protected toastService: ToastService,
private twoFactorAuthDuoComponentService: TwoFactorAuthDuoComponentService,
private destroyRef: DestroyRef,
) {}
async ngOnInit(): Promise<void> {
this.twoFactorAuthDuoComponentService
.listenForDuo2faResult$()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((duo2faResult: Duo2faResult) => {
this.tokenEmitter.emit(duo2faResult.token);
});
// flow must be launched by user so they can choose to remember the device or not.
this.duoFramelessUrl = this.providerData.AuthUrl;
}
// Called via parent two-factor-auth component.
async launchDuoFrameless(duoLaunchAction: DuoLaunchAction): Promise<void> {
switch (duoLaunchAction) {
case DuoLaunchAction.DIRECT_LAUNCH:
await this.launchDuoFramelessDirectly();
break;
case DuoLaunchAction.SINGLE_ACTION_POPOUT:
await this.twoFactorAuthDuoComponentService.openTwoFactorAuthDuoPopout?.();
break;
default:
break;
}
}
private async launchDuoFramelessDirectly(): Promise<void> {
if (this.duoFramelessUrl === null || this.duoFramelessUrl === undefined) {
this.toastService.showToast({
variant: "error",
title: "",
message: this.i18nService.t("duoHealthCheckResultsInNullAuthUrlError"),
});
return;
}
await this.twoFactorAuthDuoComponentService.launchDuoFrameless(this.duoFramelessUrl);
}
}

View File

@@ -0,0 +1,6 @@
import { TwoFactorAuthEmailComponentService } from "./two-factor-auth-email-component.service";
export class DefaultTwoFactorAuthEmailComponentService
implements TwoFactorAuthEmailComponentService {
// no default implementation
}

View File

@@ -0,0 +1,2 @@
export * from "./default-two-factor-auth-email-component.service";
export * from "./two-factor-auth-email-component.service";

View File

@@ -0,0 +1,10 @@
/**
* A service that manages all cross client functionality for the email 2FA component.
*/
export abstract class TwoFactorAuthEmailComponentService {
/**
* Optionally shows a warning to the user that they might need to popout the
* window to complete email 2FA.
*/
abstract openPopoutIfApprovedForEmail2fa?(): Promise<void>;
}

View File

@@ -0,0 +1,17 @@
<bit-form-field class="!tw-mb-0">
<bit-label>{{ "verificationCode" | i18n }}</bit-label>
<input bitInput type="text" appAutofocus appInputVerbatim [formControl]="tokenFormControl" />
</bit-form-field>
<div class="tw-mb-4">
<a
bitTypography="helper"
class="tw-text-main"
bitLink
href="#"
appStopClick
(click)="sendEmail(true)"
>
{{ "resendCode" | i18n }}
</a>
</div>

View File

@@ -0,0 +1,129 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, Input, OnInit } from "@angular/core";
import { ReactiveFormsModule, FormsModule, FormControl } from "@angular/forms";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { LoginStrategyServiceAbstraction } from "@bitwarden/auth/common";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { TwoFactorEmailRequest } from "@bitwarden/common/auth/models/request/two-factor-email.request";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import {
ButtonModule,
LinkModule,
TypographyModule,
FormFieldModule,
AsyncActionsModule,
ToastService,
} from "@bitwarden/components";
import { TwoFactorAuthEmailComponentService } from "./two-factor-auth-email-component.service";
@Component({
standalone: true,
selector: "app-two-factor-auth-email",
templateUrl: "two-factor-auth-email.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
providers: [],
})
export class TwoFactorAuthEmailComponent implements OnInit {
@Input({ required: true }) tokenFormControl: FormControl | undefined = undefined;
twoFactorEmail: string | undefined = undefined;
emailPromise: Promise<any> | undefined = undefined;
tokenValue: string = "";
constructor(
protected i18nService: I18nService,
protected twoFactorService: TwoFactorService,
protected loginStrategyService: LoginStrategyServiceAbstraction,
protected platformUtilsService: PlatformUtilsService,
protected logService: LogService,
protected apiService: ApiService,
protected appIdService: AppIdService,
private toastService: ToastService,
private twoFactorAuthEmailComponentService: TwoFactorAuthEmailComponentService,
) {}
async ngOnInit(): Promise<void> {
await this.twoFactorAuthEmailComponentService.openPopoutIfApprovedForEmail2fa?.();
const providers = await this.twoFactorService.getProviders();
if (!providers) {
throw new Error("User has no 2FA Providers");
}
const email2faProviderData = providers.get(TwoFactorProviderType.Email);
if (!email2faProviderData) {
throw new Error("Unable to retrieve email 2FA provider data");
}
this.twoFactorEmail = email2faProviderData.Email;
if (providers.size > 1) {
await this.sendEmail(false);
}
}
async sendEmail(doToast: boolean) {
if (this.emailPromise !== undefined) {
return;
}
// TODO: PM-17545 - consider building a method on the login strategy service to get a mostly
// initialized TwoFactorEmailRequest in 1 call instead of 5 like we do today.
const email = await this.loginStrategyService.getEmail();
if (email == null) {
this.toastService.showToast({
variant: "error",
title: this.i18nService.t("errorOccurred"),
message: this.i18nService.t("sessionTimeout"),
});
return;
}
try {
const request = new TwoFactorEmailRequest();
request.email = email;
request.masterPasswordHash = (await this.loginStrategyService.getMasterPasswordHash()) ?? "";
request.ssoEmail2FaSessionToken =
(await this.loginStrategyService.getSsoEmail2FaSessionToken()) ?? "";
request.deviceIdentifier = await this.appIdService.getAppId();
request.authRequestAccessCode = (await this.loginStrategyService.getAccessCode()) ?? "";
request.authRequestId = (await this.loginStrategyService.getAuthRequestId()) ?? "";
this.emailPromise = this.apiService.postTwoFactorEmail(request);
await this.emailPromise;
if (doToast) {
this.toastService.showToast({
variant: "success",
title: "",
message: this.i18nService.t("verificationCodeEmailSent", this.twoFactorEmail),
});
}
} catch (e) {
this.logService.error(e);
}
this.emailPromise = undefined;
}
}

View File

@@ -0,0 +1,12 @@
import { TwoFactorAuthWebAuthnComponentService } from "./two-factor-auth-webauthn-component.service";
export class DefaultTwoFactorAuthWebAuthnComponentService
implements TwoFactorAuthWebAuthnComponentService
{
/**
* Default implementation is to not open in a new tab.
*/
shouldOpenWebAuthnInNewTab(): boolean {
return false;
}
}

View File

@@ -0,0 +1,2 @@
export * from "./two-factor-auth-webauthn-component.service";
export * from "./default-two-factor-auth-webauthn-component.service";

View File

@@ -0,0 +1,10 @@
/**
* A service that manages all cross client functionality for the WebAuthn 2FA component.
*/
export abstract class TwoFactorAuthWebAuthnComponentService {
/**
* Determines if the WebAuthn 2FA should be opened in a new tab or can be completed in the current tab.
* In a browser extension context, we open WebAuthn in a new web client tab.
*/
abstract shouldOpenWebAuthnInNewTab(): boolean;
}

View File

@@ -0,0 +1,24 @@
<div id="web-authn-frame" class="tw-mb-3" *ngIf="!webAuthnNewTab">
<div *ngIf="!webAuthnReady" class="tw-flex tw-items-center tw-justify-center">
<i class="bwi bwi-spinner bwi-spin bwi-3x" aria-hidden="true"></i>
</div>
<iframe
id="webauthn_iframe"
sandbox="allow-scripts allow-same-origin"
[ngClass]="{ 'tw-hidden': !webAuthnReady }"
></iframe>
</div>
<ng-container *ngIf="webAuthnNewTab">
<button
class="tw-mb-3"
buttonType="primary"
[block]="true"
bitButton
type="button"
(click)="authWebAuthn()"
appStopClick
>
{{ "openInNewTab" | i18n }}
</button>
</ng-container>

View File

@@ -0,0 +1,159 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, EventEmitter, Inject, OnDestroy, OnInit, Output } from "@angular/core";
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { firstValueFrom } from "rxjs";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { WebAuthnIFrame } from "@bitwarden/common/auth/webauthn-iframe";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import {
ButtonModule,
LinkModule,
TypographyModule,
FormFieldModule,
AsyncActionsModule,
ToastService,
} from "@bitwarden/components";
import { TwoFactorAuthWebAuthnComponentService } from "./two-factor-auth-webauthn-component.service";
export interface WebAuthnResult {
token: string;
remember?: boolean;
}
@Component({
standalone: true,
selector: "app-two-factor-auth-webauthn",
templateUrl: "two-factor-auth-webauthn.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
providers: [],
})
export class TwoFactorAuthWebAuthnComponent implements OnInit, OnDestroy {
@Output() webAuthnResultEmitter = new EventEmitter<WebAuthnResult>();
@Output() webAuthnInNewTabEmitter = new EventEmitter<boolean>();
webAuthnReady = false;
webAuthnNewTab = false;
webAuthnSupported = false;
webAuthnIframe: WebAuthnIFrame | undefined = undefined;
constructor(
protected i18nService: I18nService,
protected platformUtilsService: PlatformUtilsService,
@Inject(WINDOW) protected win: Window,
protected environmentService: EnvironmentService,
protected twoFactorService: TwoFactorService,
protected route: ActivatedRoute,
private toastService: ToastService,
private twoFactorAuthWebAuthnComponentService: TwoFactorAuthWebAuthnComponentService,
private logService: LogService,
) {
this.webAuthnSupported = this.platformUtilsService.supportsWebAuthn(win);
this.webAuthnNewTab = this.twoFactorAuthWebAuthnComponentService.shouldOpenWebAuthnInNewTab();
}
async ngOnInit(): Promise<void> {
this.webAuthnInNewTabEmitter.emit(this.webAuthnNewTab);
if (this.webAuthnNewTab && this.route.snapshot.paramMap.has("webAuthnResponse")) {
this.submitWebAuthnNewTabResponse();
} else {
await this.buildWebAuthnIFrame();
}
}
private submitWebAuthnNewTabResponse() {
const webAuthnNewTabResponse = this.route.snapshot.paramMap.get("webAuthnResponse");
const remember = this.route.snapshot.paramMap.get("remember") === "true";
if (webAuthnNewTabResponse != null) {
this.webAuthnResultEmitter.emit({
token: webAuthnNewTabResponse,
remember,
});
}
}
private async buildWebAuthnIFrame() {
if (this.win != null && this.webAuthnSupported) {
const env = await firstValueFrom(this.environmentService.environment$);
const webVaultUrl = env.getWebVaultUrl();
this.webAuthnIframe = new WebAuthnIFrame(
this.win,
webVaultUrl,
this.webAuthnNewTab,
this.platformUtilsService,
this.i18nService,
(token: string) => {
this.webAuthnResultEmitter.emit({ token });
},
(error: string) => {
this.toastService.showToast({
variant: "error",
title: this.i18nService.t("errorOccurred"),
message: this.i18nService.t("webauthnCancelOrTimeout"),
});
},
(info: string) => {
if (info === "ready") {
this.webAuthnReady = true;
}
},
);
if (!this.webAuthnNewTab) {
setTimeout(async () => {
await this.authWebAuthn();
}, 500);
}
}
}
ngOnDestroy(): void {
this.cleanupWebAuthnIframe();
}
async authWebAuthn() {
const providers = await this.twoFactorService.getProviders();
if (providers == null) {
this.logService.error("No 2FA providers found. Unable to authenticate with WebAuthn.");
return;
}
const providerData = providers?.get(TwoFactorProviderType.WebAuthn);
if (!this.webAuthnSupported || this.webAuthnIframe == null) {
return;
}
this.webAuthnIframe.init(providerData);
}
private cleanupWebAuthnIframe() {
if (this.webAuthnIframe != null) {
this.webAuthnIframe.stop();
this.webAuthnIframe.cleanup();
}
}
}

View File

@@ -0,0 +1,4 @@
<bit-form-field>
<bit-label class="">{{ "verificationCode" | i18n }}</bit-label>
<input type="password" bitInput appAutofocus appInputVerbatim [formControl]="tokenFormControl" />
</bit-form-field>

View File

@@ -0,0 +1,35 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, Input } from "@angular/core";
import { ReactiveFormsModule, FormsModule, FormControl } from "@angular/forms";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import {
ButtonModule,
LinkModule,
TypographyModule,
FormFieldModule,
AsyncActionsModule,
} from "@bitwarden/components";
@Component({
standalone: true,
selector: "app-two-factor-auth-yubikey",
templateUrl: "two-factor-auth-yubikey.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
providers: [],
})
export class TwoFactorAuthYubikeyComponent {
@Input({ required: true }) tokenFormControl: FormControl | undefined = undefined;
}

View File

@@ -0,0 +1,19 @@
import {
DuoLaunchAction,
LegacyKeyMigrationAction,
TwoFactorAuthComponentService,
} from "./two-factor-auth-component.service";
export class DefaultTwoFactorAuthComponentService implements TwoFactorAuthComponentService {
shouldCheckForWebAuthnQueryParamResponse() {
return false;
}
determineLegacyKeyMigrationAction() {
return LegacyKeyMigrationAction.PREVENT_LOGIN_AND_SHOW_REQUIRE_MIGRATION_WARNING;
}
determineDuoLaunchAction(): DuoLaunchAction {
return DuoLaunchAction.DIRECT_LAUNCH;
}
}

View File

@@ -0,0 +1,6 @@
export * from "./two-factor-auth-component.service";
export * from "./default-two-factor-auth-component.service";
export * from "./two-factor-auth.component";
export * from "./two-factor-auth.guard";
export * from "./child-components";

View File

@@ -0,0 +1,66 @@
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
export enum LegacyKeyMigrationAction {
PREVENT_LOGIN_AND_SHOW_REQUIRE_MIGRATION_WARNING,
NAVIGATE_TO_MIGRATION_COMPONENT,
}
export enum DuoLaunchAction {
DIRECT_LAUNCH,
SINGLE_ACTION_POPOUT,
}
/**
* Manages all cross client functionality so we can have a single two factor auth component
* implementation for all clients.
*/
export abstract class TwoFactorAuthComponentService {
/**
* Determines if the client should check for a webauthn response on init.
* Currently, only the extension should check during component initialization.
*/
abstract shouldCheckForWebAuthnQueryParamResponse(): boolean;
/**
* Extends the popup width if required.
* Some client specific situations require the popup to be wider than the default width.
*/
abstract extendPopupWidthIfRequired?(
selected2faProviderType: TwoFactorProviderType,
): Promise<void>;
/**
* Removes the popup width extension.
*/
abstract removePopupWidthExtension?(): void;
/**
* We used to use the user's master key to encrypt their data. We deprecated that approach
* and now use a user key. This method should be called if we detect that the user
* is still using the old master key encryption scheme (server sends down a flag to
* indicate this). This method then determines what action to take based on the client.
*
* We have two possible actions:
* 1. Prevent the user from logging in and show a warning that they need to migrate their key on the web client today.
* 2. Navigate the user to the key migration component on the web client.
*/
abstract determineLegacyKeyMigrationAction(): LegacyKeyMigrationAction;
/**
* Optionally closes any single action popouts (extension only).
* @returns true if we are in a single action popout and it was closed, false otherwise.
*/
abstract closeSingleActionPopouts?(): Promise<boolean>;
/**
* Optionally refreshes any open windows (exempts current window).
* Only defined on the extension client for the goal of refreshing sidebars.
*/
abstract reloadOpenWindows?(): void;
/**
* Determines the action to take when launching the Duo flow.
* The extension has to popout the flow, while other clients can launch it directly.
*/
abstract determineDuoLaunchAction(): DuoLaunchAction;
}

View File

@@ -0,0 +1,108 @@
<ng-container *ngIf="loading">
<div class="tw-flex tw-items-center tw-justify-center">
<i class="bwi bwi-spinner bwi-spin bwi-3x" aria-hidden="true"></i>
</div>
</ng-container>
<ng-container *ngIf="!loading">
<form
[bitSubmit]="submit"
[formGroup]="form"
autocomplete="off"
(keydown.enter)="handleEnterKeyPress()"
>
<app-two-factor-auth-email
[tokenFormControl]="tokenFormControl"
*ngIf="selectedProviderType === providerType.Email"
/>
<app-two-factor-auth-authenticator
[tokenFormControl]="tokenFormControl"
*ngIf="selectedProviderType === providerType.Authenticator"
/>
<app-two-factor-auth-yubikey
[tokenFormControl]="tokenFormControl"
*ngIf="selectedProviderType === providerType.Yubikey"
/>
<app-two-factor-auth-duo
(tokenEmitter)="submit($event)"
[providerData]="selectedProviderData"
*ngIf="
selectedProviderType === providerType.OrganizationDuo ||
selectedProviderType === providerType.Duo
"
#duoComponent
/>
<bit-form-control *ngIf="!hideRememberMe()">
<bit-label>{{ "dontAskAgainOnThisDeviceFor30Days" | i18n }}</bit-label>
<input type="checkbox" bitCheckbox formControlName="remember" />
</bit-form-control>
<app-two-factor-auth-webauthn
(webAuthnResultEmitter)="submit($event.token, $event.remember)"
(webAuthnInNewTabEmitter)="webAuthInNewTab = $event"
*ngIf="selectedProviderType === providerType.WebAuthn"
/>
<ng-container *ngIf="selectedProviderType == null">
<p bitTypography="body1">{{ "noTwoStepProviders" | i18n }}</p>
<p bitTypography="body1">{{ "noTwoStepProviders2" | i18n }}</p>
</ng-container>
<!-- Buttons -->
<div class="tw-flex tw-flex-col tw-space-y-3">
<button
type="submit"
buttonType="primary"
bitButton
bitFormButton
#continueButton
*ngIf="showContinueButton()"
>
<span> {{ "continueLoggingIn" | i18n }} </span>
</button>
<button
type="button"
buttonType="primary"
bitButton
(click)="launchDuo()"
*ngIf="
selectedProviderType === providerType.Duo ||
selectedProviderType === providerType.OrganizationDuo
"
>
<span *ngIf="duoLaunchAction === DuoLaunchAction.DIRECT_LAUNCH">
{{ "launchDuo" | i18n }}</span
>
<span *ngIf="duoLaunchAction === DuoLaunchAction.SINGLE_ACTION_POPOUT">
{{ "popoutExtension" | i18n }}</span
>
</button>
<p class="tw-text-center tw-mb-0">{{ "or" | i18n }}</p>
<button
type="button"
buttonType="secondary"
bitButton
bitFormButton
*ngIf="twoFactorProviders?.size > 1"
(click)="selectOtherTwoFactorMethod()"
>
<span> {{ "selectAnotherMethod" | i18n }} </span>
</button>
<button
type="button"
buttonType="secondary"
bitButton
bitFormButton
(click)="use2faRecoveryCode()"
>
<span> {{ "useYourRecoveryCode" | i18n }} </span>
</button>
</div>
</form>
</ng-container>

View File

@@ -0,0 +1,455 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Component } from "@angular/core";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { ActivatedRoute, convertToParamMap, Router } from "@angular/router";
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject } from "rxjs";
// eslint-disable-next-line no-restricted-imports
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
import {
LoginStrategyServiceAbstraction,
LoginEmailServiceAbstraction,
FakeKeyConnectorUserDecryptionOption as KeyConnectorUserDecryptionOption,
FakeTrustedDeviceUserDecryptionOption as TrustedDeviceUserDecryptionOption,
FakeUserDecryptionOptions as UserDecryptionOptions,
UserDecryptionOptionsServiceAbstraction,
LoginSuccessHandlerService,
} from "@bitwarden/auth/common";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction";
import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/sso-login.service.abstraction";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { AuthenticationType } from "@bitwarden/common/auth/enums/authentication-type";
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/master-password/fake-master-password.service";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { DialogService, ToastService } from "@bitwarden/components";
import { AnonLayoutWrapperDataService } from "../anon-layout/anon-layout-wrapper-data.service";
import { TwoFactorAuthComponentService } from "./two-factor-auth-component.service";
import { TwoFactorAuthComponent } from "./two-factor-auth.component";
@Component({})
class TestTwoFactorComponent extends TwoFactorAuthComponent {}
describe("TwoFactorAuthComponent", () => {
let component: TestTwoFactorComponent;
let fixture: ComponentFixture<TestTwoFactorComponent>;
const userId = "userId" as UserId;
// Mock Services
let mockLoginStrategyService: MockProxy<LoginStrategyServiceAbstraction>;
let mockRouter: MockProxy<Router>;
let mockI18nService: MockProxy<I18nService>;
let mockApiService: MockProxy<ApiService>;
let mockPlatformUtilsService: MockProxy<PlatformUtilsService>;
let mockWin: MockProxy<Window>;
let mockStateService: MockProxy<StateService>;
let mockLogService: MockProxy<LogService>;
let mockTwoFactorService: MockProxy<TwoFactorService>;
let mockAppIdService: MockProxy<AppIdService>;
let mockLoginEmailService: MockProxy<LoginEmailServiceAbstraction>;
let mockUserDecryptionOptionsService: MockProxy<UserDecryptionOptionsServiceAbstraction>;
let mockSsoLoginService: MockProxy<SsoLoginServiceAbstraction>;
let mockMasterPasswordService: FakeMasterPasswordService;
let mockAccountService: FakeAccountService;
let mockDialogService: MockProxy<DialogService>;
let mockToastService: MockProxy<ToastService>;
let mockTwoFactorAuthCompService: MockProxy<TwoFactorAuthComponentService>;
let anonLayoutWrapperDataService: MockProxy<AnonLayoutWrapperDataService>;
let mockEnvService: MockProxy<EnvironmentService>;
let mockLoginSuccessHandlerService: MockProxy<LoginSuccessHandlerService>;
let mockUserDecryptionOpts: {
noMasterPassword: UserDecryptionOptions;
withMasterPassword: UserDecryptionOptions;
withMasterPasswordAndTrustedDevice: UserDecryptionOptions;
withMasterPasswordAndTrustedDeviceWithManageResetPassword: UserDecryptionOptions;
withMasterPasswordAndKeyConnector: UserDecryptionOptions;
noMasterPasswordWithTrustedDevice: UserDecryptionOptions;
noMasterPasswordWithTrustedDeviceWithManageResetPassword: UserDecryptionOptions;
noMasterPasswordWithKeyConnector: UserDecryptionOptions;
};
let selectedUserDecryptionOptions: BehaviorSubject<UserDecryptionOptions>;
beforeEach(() => {
mockLoginStrategyService = mock<LoginStrategyServiceAbstraction>();
mockRouter = mock<Router>();
mockI18nService = mock<I18nService>();
mockApiService = mock<ApiService>();
mockPlatformUtilsService = mock<PlatformUtilsService>();
mockWin = mock<Window>();
mockStateService = mock<StateService>();
mockLogService = mock<LogService>();
mockTwoFactorService = mock<TwoFactorService>();
mockAppIdService = mock<AppIdService>();
mockLoginEmailService = mock<LoginEmailServiceAbstraction>();
mockUserDecryptionOptionsService = mock<UserDecryptionOptionsServiceAbstraction>();
mockSsoLoginService = mock<SsoLoginServiceAbstraction>();
mockAccountService = mockAccountServiceWith(userId);
mockMasterPasswordService = new FakeMasterPasswordService();
mockDialogService = mock<DialogService>();
mockToastService = mock<ToastService>();
mockTwoFactorAuthCompService = mock<TwoFactorAuthComponentService>();
mockEnvService = mock<EnvironmentService>();
mockLoginSuccessHandlerService = mock<LoginSuccessHandlerService>();
anonLayoutWrapperDataService = mock<AnonLayoutWrapperDataService>();
mockUserDecryptionOpts = {
noMasterPassword: new UserDecryptionOptions({
hasMasterPassword: false,
trustedDeviceOption: undefined,
keyConnectorOption: undefined,
}),
withMasterPassword: new UserDecryptionOptions({
hasMasterPassword: true,
trustedDeviceOption: undefined,
keyConnectorOption: undefined,
}),
withMasterPasswordAndTrustedDevice: new UserDecryptionOptions({
hasMasterPassword: true,
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false, false),
keyConnectorOption: undefined,
}),
withMasterPasswordAndTrustedDeviceWithManageResetPassword: new UserDecryptionOptions({
hasMasterPassword: true,
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true, false),
keyConnectorOption: undefined,
}),
withMasterPasswordAndKeyConnector: new UserDecryptionOptions({
hasMasterPassword: true,
trustedDeviceOption: undefined,
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
}),
noMasterPasswordWithTrustedDevice: new UserDecryptionOptions({
hasMasterPassword: false,
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false, false),
keyConnectorOption: undefined,
}),
noMasterPasswordWithTrustedDeviceWithManageResetPassword: new UserDecryptionOptions({
hasMasterPassword: false,
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true, false),
keyConnectorOption: undefined,
}),
noMasterPasswordWithKeyConnector: new UserDecryptionOptions({
hasMasterPassword: false,
trustedDeviceOption: undefined,
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
}),
};
selectedUserDecryptionOptions = new BehaviorSubject<UserDecryptionOptions>(undefined);
mockUserDecryptionOptionsService.userDecryptionOptions$ = selectedUserDecryptionOptions;
TestBed.configureTestingModule({
declarations: [TestTwoFactorComponent],
providers: [
{ provide: LoginStrategyServiceAbstraction, useValue: mockLoginStrategyService },
{ provide: Router, useValue: mockRouter },
{ provide: I18nService, useValue: mockI18nService },
{ provide: ApiService, useValue: mockApiService },
{ provide: PlatformUtilsService, useValue: mockPlatformUtilsService },
{ provide: WINDOW, useValue: mockWin },
{ provide: StateService, useValue: mockStateService },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
// Default to standard 2FA flow - not SSO + 2FA
queryParamMap: convertToParamMap({ sso: "false" }),
},
},
},
{ provide: LogService, useValue: mockLogService },
{ provide: TwoFactorService, useValue: mockTwoFactorService },
{ provide: AppIdService, useValue: mockAppIdService },
{ provide: LoginEmailServiceAbstraction, useValue: mockLoginEmailService },
{
provide: UserDecryptionOptionsServiceAbstraction,
useValue: mockUserDecryptionOptionsService,
},
{ provide: SsoLoginServiceAbstraction, useValue: mockSsoLoginService },
{ provide: InternalMasterPasswordServiceAbstraction, useValue: mockMasterPasswordService },
{ provide: AccountService, useValue: mockAccountService },
{ provide: DialogService, useValue: mockDialogService },
{ provide: ToastService, useValue: mockToastService },
{ provide: TwoFactorAuthComponentService, useValue: mockTwoFactorAuthCompService },
{ provide: EnvironmentService, useValue: mockEnvService },
{ provide: AnonLayoutWrapperDataService, useValue: anonLayoutWrapperDataService },
{ provide: LoginSuccessHandlerService, useValue: mockLoginSuccessHandlerService },
],
});
fixture = TestBed.createComponent(TestTwoFactorComponent);
component = fixture.componentInstance;
});
afterEach(() => {
// Reset all mocks after each test
jest.resetAllMocks();
});
it("should create", () => {
expect(component).toBeTruthy();
});
// Shared tests
const testChangePasswordOnSuccessfulLogin = () => {
it("navigates to the component's defined change password route when user doesn't have a MP and key connector isn't enabled", async () => {
// Act
await component.submit("testToken");
// Assert
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["set-password"], {
queryParams: {
identifier: component.orgSsoIdentifier,
},
});
});
};
const testForceResetOnSuccessfulLogin = (reasonString: string) => {
it(`navigates to the component's defined forcePasswordResetRoute route when response.forcePasswordReset is ${reasonString}`, async () => {
// Act
await component.submit("testToken");
// expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["update-temp-password"], {
queryParams: {
identifier: component.orgSsoIdentifier,
},
});
});
};
describe("Standard 2FA scenarios", () => {
describe("submit", () => {
const token = "testToken";
const remember = false;
const currentAuthTypeSubject = new BehaviorSubject<AuthenticationType>(
AuthenticationType.Password,
);
beforeEach(() => {
selectedUserDecryptionOptions.next(mockUserDecryptionOpts.withMasterPassword);
mockLoginStrategyService.currentAuthType$ = currentAuthTypeSubject.asObservable();
});
it("calls authService.logInTwoFactor with correct parameters when form is submitted", async () => {
// Arrange
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(new AuthResult());
// Act
await component.submit(token, remember);
// Assert
expect(mockLoginStrategyService.logInTwoFactor).toHaveBeenCalledWith(
new TokenTwoFactorRequest(component.selectedProviderType, token, remember),
"",
);
});
it("calls loginEmailService.clearValues() when login is successful", async () => {
// Arrange
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(new AuthResult());
// spy on loginEmailService.clearValues
const clearValuesSpy = jest.spyOn(mockLoginEmailService, "clearValues");
// Act
await component.submit(token, remember);
// Assert
expect(clearValuesSpy).toHaveBeenCalled();
});
describe("Set Master Password scenarios", () => {
beforeEach(() => {
const authResult = new AuthResult();
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(authResult);
});
describe("Given user needs to set a master password", () => {
beforeEach(() => {
// Only need to test the case where the user has no master password to test the primary change mp flow here
selectedUserDecryptionOptions.next(mockUserDecryptionOpts.noMasterPassword);
});
testChangePasswordOnSuccessfulLogin();
});
it("does not navigate to the change password route when the user has key connector even if user has no master password", async () => {
selectedUserDecryptionOptions.next(
mockUserDecryptionOpts.noMasterPasswordWithKeyConnector,
);
await component.submit(token, remember);
expect(mockRouter.navigate).not.toHaveBeenCalledWith(["set-password"], {
queryParams: {
identifier: component.orgSsoIdentifier,
},
});
});
});
describe("Force Master Password Reset scenarios", () => {
[
ForceSetPasswordReason.AdminForcePasswordReset,
ForceSetPasswordReason.WeakMasterPassword,
].forEach((forceResetPasswordReason) => {
const reasonString = ForceSetPasswordReason[forceResetPasswordReason];
beforeEach(() => {
// use standard user with MP because this test is not concerned with password reset.
selectedUserDecryptionOptions.next(mockUserDecryptionOpts.withMasterPassword);
const authResult = new AuthResult();
authResult.forcePasswordReset = forceResetPasswordReason;
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(authResult);
});
testForceResetOnSuccessfulLogin(reasonString);
});
});
it("navigates to the component's defined success route (vault is default) when the login is successful", async () => {
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(new AuthResult());
// Act
await component.submit("testToken");
// Assert
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["vault"], {
queryParams: {
identifier: component.orgSsoIdentifier,
},
});
});
it.each([
[AuthenticationType.Sso, "lock"],
[AuthenticationType.UserApiKey, "lock"],
])(
"navigates to the lock component when the authentication type is %s",
async (authType, expectedRoute) => {
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(new AuthResult());
currentAuthTypeSubject.next(authType);
// Act
await component.submit("testToken");
// Assert
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["lock"], {
queryParams: {
identifier: component.orgSsoIdentifier,
},
});
},
);
});
});
describe("SSO > 2FA scenarios", () => {
beforeEach(() => {
const mockActivatedRoute = TestBed.inject(ActivatedRoute);
mockActivatedRoute.snapshot.queryParamMap.get = jest.fn().mockReturnValue("true");
});
describe("submit", () => {
const token = "testToken";
const remember = false;
describe("Trusted Device Encryption scenarios", () => {
describe("Given Trusted Device Encryption is enabled and user needs to set a master password", () => {
beforeEach(() => {
selectedUserDecryptionOptions.next(
mockUserDecryptionOpts.noMasterPasswordWithTrustedDeviceWithManageResetPassword,
);
const authResult = new AuthResult();
authResult.userId = userId;
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(authResult);
});
it("navigates to the login-initiated route and sets correct flag when user doesn't have a MP and key connector isn't enabled", async () => {
// Act
await component.submit(token, remember);
// Assert
expect(mockMasterPasswordService.mock.setForceSetPasswordReason).toHaveBeenCalledWith(
ForceSetPasswordReason.TdeUserWithoutPasswordHasPasswordResetPermission,
userId,
);
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["login-initiated"]);
});
});
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is required", () => {
[
ForceSetPasswordReason.AdminForcePasswordReset,
ForceSetPasswordReason.WeakMasterPassword,
].forEach((forceResetPasswordReason) => {
const reasonString = ForceSetPasswordReason[forceResetPasswordReason];
beforeEach(() => {
// use standard user with MP because this test is not concerned with password reset.
selectedUserDecryptionOptions.next(
mockUserDecryptionOpts.withMasterPasswordAndTrustedDevice,
);
const authResult = new AuthResult();
authResult.forcePasswordReset = forceResetPasswordReason;
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(authResult);
});
testForceResetOnSuccessfulLogin(reasonString);
});
});
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is not required", () => {
let authResult;
beforeEach(() => {
selectedUserDecryptionOptions.next(
mockUserDecryptionOpts.withMasterPasswordAndTrustedDevice,
);
authResult = new AuthResult();
authResult.forcePasswordReset = ForceSetPasswordReason.None;
mockLoginStrategyService.logInTwoFactor.mockResolvedValue(authResult);
});
it("navigates to the login-initiated route when login is successful", async () => {
await component.submit(token, remember);
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
expect(mockRouter.navigate).toHaveBeenCalledWith(["login-initiated"]);
});
});
});
});
});
});

View File

@@ -0,0 +1,591 @@
import { CommonModule } from "@angular/common";
import {
Component,
DestroyRef,
ElementRef,
Inject,
OnDestroy,
OnInit,
ViewChild,
} from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { FormBuilder, ReactiveFormsModule, Validators } from "@angular/forms";
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { lastValueFrom, firstValueFrom } from "rxjs";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
import {
LoginStrategyServiceAbstraction,
LoginEmailServiceAbstraction,
UserDecryptionOptionsServiceAbstraction,
TrustedDeviceUserDecryptionOption,
UserDecryptionOptions,
LoginSuccessHandlerService,
} from "@bitwarden/auth/common";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction";
import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/sso-login.service.abstraction";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { AuthenticationType } from "@bitwarden/common/auth/enums/authentication-type";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { UserId } from "@bitwarden/common/types/guid";
import {
AsyncActionsModule,
ButtonModule,
CheckboxModule,
DialogService,
FormFieldModule,
ToastService,
} from "@bitwarden/components";
import { AnonLayoutWrapperDataService } from "../anon-layout/anon-layout-wrapper-data.service";
import {
TwoFactorAuthAuthenticatorIcon,
TwoFactorAuthEmailIcon,
TwoFactorAuthWebAuthnIcon,
TwoFactorAuthSecurityKeyIcon,
TwoFactorAuthDuoIcon,
} from "../icons/two-factor-auth";
import { TwoFactorAuthAuthenticatorComponent } from "./child-components/two-factor-auth-authenticator.component";
import { TwoFactorAuthDuoComponent } from "./child-components/two-factor-auth-duo/two-factor-auth-duo.component";
import { TwoFactorAuthEmailComponent } from "./child-components/two-factor-auth-email/two-factor-auth-email.component";
import { TwoFactorAuthWebAuthnComponent } from "./child-components/two-factor-auth-webauthn/two-factor-auth-webauthn.component";
import { TwoFactorAuthYubikeyComponent } from "./child-components/two-factor-auth-yubikey.component";
import {
DuoLaunchAction,
LegacyKeyMigrationAction,
TwoFactorAuthComponentService,
} from "./two-factor-auth-component.service";
import {
TwoFactorOptionsComponent,
TwoFactorOptionsDialogResult,
} from "./two-factor-options.component";
@Component({
standalone: true,
selector: "app-two-factor-auth",
templateUrl: "two-factor-auth.component.html",
imports: [
CommonModule,
JslibModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
RouterLink,
CheckboxModule,
ButtonModule,
TwoFactorOptionsComponent, // used as dialog
TwoFactorAuthAuthenticatorComponent,
TwoFactorAuthEmailComponent,
TwoFactorAuthDuoComponent,
TwoFactorAuthYubikeyComponent,
TwoFactorAuthWebAuthnComponent,
],
providers: [],
})
export class TwoFactorAuthComponent implements OnInit, OnDestroy {
@ViewChild("continueButton", { read: ElementRef, static: false }) continueButton:
| ElementRef
| undefined = undefined;
loading = true;
orgSsoIdentifier: string | undefined = undefined;
providerType = TwoFactorProviderType;
selectedProviderType: TwoFactorProviderType = TwoFactorProviderType.Authenticator;
// TODO: PM-17176 - build more specific type for 2FA metadata
twoFactorProviders: Map<TwoFactorProviderType, { [key: string]: string }> | null = null;
selectedProviderData: { [key: string]: string } | undefined;
@ViewChild("duoComponent") duoComponent!: TwoFactorAuthDuoComponent;
form = this.formBuilder.group({
token: [
"",
{
validators: [Validators.required],
updateOn: "submit",
},
],
remember: [false],
});
get tokenFormControl() {
return this.form.controls.token;
}
get rememberFormControl() {
return this.form.controls.remember;
}
formPromise: Promise<any> | undefined;
duoLaunchAction: DuoLaunchAction | undefined = undefined;
DuoLaunchAction = DuoLaunchAction;
webAuthInNewTab = false;
private authenticationSessionTimeoutRoute = "authentication-timeout";
constructor(
private loginStrategyService: LoginStrategyServiceAbstraction,
private router: Router,
private i18nService: I18nService,
private platformUtilsService: PlatformUtilsService,
private dialogService: DialogService,
private activatedRoute: ActivatedRoute,
private logService: LogService,
private twoFactorService: TwoFactorService,
private loginEmailService: LoginEmailServiceAbstraction,
private userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction,
private ssoLoginService: SsoLoginServiceAbstraction,
private masterPasswordService: InternalMasterPasswordServiceAbstraction,
private accountService: AccountService,
private formBuilder: FormBuilder,
@Inject(WINDOW) protected win: Window,
private toastService: ToastService,
private twoFactorAuthComponentService: TwoFactorAuthComponentService,
private destroyRef: DestroyRef,
private anonLayoutWrapperDataService: AnonLayoutWrapperDataService,
private environmentService: EnvironmentService,
private loginSuccessHandlerService: LoginSuccessHandlerService,
) {}
async ngOnInit() {
this.orgSsoIdentifier =
this.activatedRoute.snapshot.queryParamMap.get("identifier") ?? undefined;
this.listenForAuthnSessionTimeout();
await this.setSelected2faProviderType();
await this.set2faProvidersAndData();
await this.setAnonLayoutDataByTwoFactorProviderType();
await this.twoFactorAuthComponentService.extendPopupWidthIfRequired?.(
this.selectedProviderType,
);
this.duoLaunchAction = this.twoFactorAuthComponentService.determineDuoLaunchAction();
this.loading = false;
}
private async setSelected2faProviderType() {
const webAuthnSupported = this.platformUtilsService.supportsWebAuthn(this.win);
if (
this.twoFactorAuthComponentService.shouldCheckForWebAuthnQueryParamResponse() &&
webAuthnSupported
) {
const webAuthn2faResponse =
this.activatedRoute.snapshot.queryParamMap.get("webAuthnResponse");
if (webAuthn2faResponse) {
this.selectedProviderType = TwoFactorProviderType.WebAuthn;
return;
}
}
this.selectedProviderType = await this.twoFactorService.getDefaultProvider(webAuthnSupported);
}
private async set2faProvidersAndData() {
this.twoFactorProviders = await this.twoFactorService.getProviders();
const providerData = this.twoFactorProviders?.get(this.selectedProviderType);
this.selectedProviderData = providerData;
}
private listenForAuthnSessionTimeout() {
this.loginStrategyService.authenticationSessionTimeout$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(async (expired) => {
if (!expired) {
return;
}
try {
await this.router.navigate([this.authenticationSessionTimeoutRoute]);
} catch (err) {
this.logService.error(
`Failed to navigate to ${this.authenticationSessionTimeoutRoute} route`,
err,
);
}
});
}
submit = async (token?: string, remember?: boolean) => {
// 2FA submission either comes via programmatic submission for flows like
// WebAuthn or Duo, or via the form submission for other 2FA providers.
// So, we have to figure out whether we need to validate the form or not.
let tokenValue: string;
if (token !== undefined) {
if (token === "" || token === null) {
this.toastService.showToast({
variant: "error",
title: this.i18nService.t("errorOccurred"),
message: this.i18nService.t("verificationCodeRequired"),
});
return;
}
// Token has been passed in so no need to validate the form
tokenValue = token;
} else {
// We support programmatic submission via enter key press, but we only update on submit
// so we have to manually update the form here for the invalid check to be accurate.
this.tokenFormControl.markAsTouched();
this.tokenFormControl.markAsDirty();
this.tokenFormControl.updateValueAndValidity();
// Token has not been passed in ensure form is valid before proceeding.
if (this.form.invalid) {
// returning as form validation will show the relevant errors.
return;
}
// This shouldn't be possible w/ the required form validation, but
// to satisfy strict TS checks, have to check for null here.
const tokenFormValue = this.tokenFormControl.value;
if (!tokenFormValue) {
return;
}
tokenValue = tokenFormValue.trim();
}
// In all flows but WebAuthn, the remember value is taken from the form.
const rememberValue = remember ?? this.rememberFormControl.value ?? false;
try {
this.formPromise = this.loginStrategyService.logInTwoFactor(
new TokenTwoFactorRequest(this.selectedProviderType, tokenValue, rememberValue),
"", // TODO: PM-15162 - deprecate captchaResponse
);
const authResult: AuthResult = await this.formPromise;
this.logService.info("Successfully submitted two factor token");
await this.handleAuthResult(authResult);
} catch {
this.logService.error("Error submitting two factor token");
this.toastService.showToast({
variant: "error",
title: this.i18nService.t("errorOccurred"),
message: this.i18nService.t("invalidVerificationCode"),
});
}
};
async selectOtherTwoFactorMethod() {
const dialogRef = TwoFactorOptionsComponent.open(this.dialogService);
const response: TwoFactorOptionsDialogResult | string | undefined = await lastValueFrom(
dialogRef.closed,
);
if (response !== undefined && response !== null && typeof response !== "string") {
const providerData = await this.twoFactorService.getProviders().then((providers) => {
return providers?.get(response.type);
});
this.selectedProviderData = providerData;
this.selectedProviderType = response.type;
await this.setAnonLayoutDataByTwoFactorProviderType();
this.form.reset();
this.form.updateValueAndValidity();
}
}
async launchDuo() {
if (this.duoComponent != null && this.duoLaunchAction !== undefined) {
await this.duoComponent.launchDuoFrameless(this.duoLaunchAction);
}
}
protected async handleMigrateEncryptionKey(result: AuthResult): Promise<boolean> {
if (!result.requiresEncryptionKeyMigration) {
return false;
}
// Migration is forced so prevent login via return
const legacyKeyMigrationAction: LegacyKeyMigrationAction =
this.twoFactorAuthComponentService.determineLegacyKeyMigrationAction();
switch (legacyKeyMigrationAction) {
case LegacyKeyMigrationAction.NAVIGATE_TO_MIGRATION_COMPONENT:
await this.router.navigate(["migrate-legacy-encryption"]);
break;
case LegacyKeyMigrationAction.PREVENT_LOGIN_AND_SHOW_REQUIRE_MIGRATION_WARNING:
this.toastService.showToast({
variant: "error",
title: this.i18nService.t("errorOccured"),
message: this.i18nService.t("encryptionKeyMigrationRequired"),
});
break;
}
return true;
}
async setAnonLayoutDataByTwoFactorProviderType() {
switch (this.selectedProviderType) {
case TwoFactorProviderType.Authenticator:
this.anonLayoutWrapperDataService.setAnonLayoutWrapperData({
pageSubtitle: this.i18nService.t("enterTheCodeFromYourAuthenticatorApp"),
pageIcon: TwoFactorAuthAuthenticatorIcon,
});
break;
case TwoFactorProviderType.Email:
this.anonLayoutWrapperDataService.setAnonLayoutWrapperData({
pageSubtitle: this.i18nService.t("enterTheCodeSentToYourEmail"),
pageIcon: TwoFactorAuthEmailIcon,
});
break;
case TwoFactorProviderType.Duo:
case TwoFactorProviderType.OrganizationDuo:
this.anonLayoutWrapperDataService.setAnonLayoutWrapperData({
pageSubtitle: this.i18nService.t("duoTwoFactorRequiredPageSubtitle"),
pageIcon: TwoFactorAuthDuoIcon,
});
break;
case TwoFactorProviderType.Yubikey:
this.anonLayoutWrapperDataService.setAnonLayoutWrapperData({
pageSubtitle: this.i18nService.t("pressYourYubiKeyToAuthenticate"),
pageIcon: TwoFactorAuthSecurityKeyIcon,
});
break;
case TwoFactorProviderType.WebAuthn:
this.anonLayoutWrapperDataService.setAnonLayoutWrapperData({
pageSubtitle: this.i18nService.t("followTheStepsBelowToFinishLoggingIn"),
pageIcon: TwoFactorAuthWebAuthnIcon,
});
break;
default:
this.logService.error(
"setAnonLayoutDataByTwoFactorProviderType: Unhandled 2FA provider type",
this.selectedProviderType,
);
break;
}
}
private async handleAuthResult(authResult: AuthResult) {
if (await this.handleMigrateEncryptionKey(authResult)) {
return; // stop login process
}
// User is fully logged in so handle any post login logic before executing navigation
await this.loginSuccessHandlerService.run(authResult.userId);
this.loginEmailService.clearValues();
// Save off the OrgSsoIdentifier for use in the TDE flows
// - TDE login decryption options component
// - Browser SSO on extension open
if (this.orgSsoIdentifier !== undefined) {
const userId = (await firstValueFrom(this.accountService.activeAccount$))?.id;
await this.ssoLoginService.setActiveUserOrganizationSsoIdentifier(
this.orgSsoIdentifier,
userId,
);
}
// note: this flow affects both TDE & standard users
if (this.isForcePasswordResetRequired(authResult)) {
return await this.handleForcePasswordReset(this.orgSsoIdentifier);
}
const userDecryptionOpts = await firstValueFrom(
this.userDecryptionOptionsService.userDecryptionOptions$,
);
const tdeEnabled = await this.isTrustedDeviceEncEnabled(userDecryptionOpts.trustedDeviceOption);
if (tdeEnabled) {
return await this.handleTrustedDeviceEncryptionEnabled(authResult.userId, userDecryptionOpts);
}
// User must set password if they don't have one and they aren't using either TDE or key connector.
const requireSetPassword =
!userDecryptionOpts.hasMasterPassword && userDecryptionOpts.keyConnectorOption === undefined;
if (requireSetPassword || authResult.resetMasterPassword) {
// Change implies going no password -> password in this case
return await this.handleChangePasswordRequired(this.orgSsoIdentifier);
}
this.twoFactorAuthComponentService.reloadOpenWindows?.();
const inSingleActionPopoutWhichWasClosed =
await this.twoFactorAuthComponentService.closeSingleActionPopouts?.();
if (inSingleActionPopoutWhichWasClosed) {
// No need to execute navigation as the single action popout was closed
return;
}
const defaultSuccessRoute = await this.determineDefaultSuccessRoute();
await this.router.navigate([defaultSuccessRoute], {
queryParams: {
identifier: this.orgSsoIdentifier,
},
});
}
private async determineDefaultSuccessRoute(): Promise<string> {
const authType = await firstValueFrom(this.loginStrategyService.currentAuthType$);
if (authType == AuthenticationType.Sso || authType == AuthenticationType.UserApiKey) {
return "lock";
}
return "vault";
}
private async isTrustedDeviceEncEnabled(
trustedDeviceOption: TrustedDeviceUserDecryptionOption | undefined,
): Promise<boolean> {
const ssoTo2faFlowActive = this.activatedRoute.snapshot.queryParamMap.get("sso") === "true";
return ssoTo2faFlowActive && trustedDeviceOption !== undefined;
}
private async handleTrustedDeviceEncryptionEnabled(
userId: UserId,
userDecryptionOpts: UserDecryptionOptions,
): Promise<void> {
// Tde offboarding takes precedence
if (
!userDecryptionOpts.hasMasterPassword &&
userDecryptionOpts.trustedDeviceOption?.isTdeOffboarding
) {
await this.masterPasswordService.setForceSetPasswordReason(
ForceSetPasswordReason.TdeOffboarding,
userId,
);
} else if (
!userDecryptionOpts.hasMasterPassword &&
userDecryptionOpts.trustedDeviceOption?.hasManageResetPasswordPermission
) {
// If user doesn't have a MP, but has reset password permission, they must set a MP
// Set flag so that auth guard can redirect to set password screen after decryption (trusted or untrusted device)
// Note: we cannot directly navigate to the set password screen in this scenario as we are in a pre-decryption state, and
// if you try to set a new MP before decrypting, you will invalidate the user's data by making a new user key.
await this.masterPasswordService.setForceSetPasswordReason(
ForceSetPasswordReason.TdeUserWithoutPasswordHasPasswordResetPermission,
userId,
);
}
this.twoFactorAuthComponentService.reloadOpenWindows?.();
const inSingleActionPopoutWhichWasClosed =
await this.twoFactorAuthComponentService.closeSingleActionPopouts?.();
if (inSingleActionPopoutWhichWasClosed) {
// No need to execute navigation as the single action popout was closed
return;
}
await this.router.navigate(["login-initiated"]);
}
private async handleChangePasswordRequired(orgIdentifier: string | undefined) {
await this.router.navigate(["set-password"], {
queryParams: {
identifier: orgIdentifier,
},
});
}
/**
* Determines if a user needs to reset their password based on certain conditions.
* Users can be forced to reset their password via an admin or org policy disallowing weak passwords.
* Note: this is different from the SSO component login flow as a user can
* login with MP and then have to pass 2FA to finish login and we can actually
* evaluate if they have a weak password at that time.
*
* @param {AuthResult} authResult - The authentication result.
* @returns {boolean} Returns true if a password reset is required, false otherwise.
*/
private isForcePasswordResetRequired(authResult: AuthResult): boolean {
const forceResetReasons = [
ForceSetPasswordReason.AdminForcePasswordReset,
ForceSetPasswordReason.WeakMasterPassword,
];
return forceResetReasons.includes(authResult.forcePasswordReset);
}
private async handleForcePasswordReset(orgIdentifier: string | undefined) {
await this.router.navigate(["update-temp-password"], {
queryParams: {
identifier: orgIdentifier,
},
});
}
showContinueButton() {
return (
this.selectedProviderType != null &&
this.selectedProviderType !== TwoFactorProviderType.WebAuthn &&
this.selectedProviderType !== TwoFactorProviderType.Duo &&
this.selectedProviderType !== TwoFactorProviderType.OrganizationDuo
);
}
hideRememberMe() {
// Don't show remember for me for scenarios where we have to popout the extension
return (
((this.selectedProviderType === TwoFactorProviderType.Duo ||
this.selectedProviderType === TwoFactorProviderType.OrganizationDuo) &&
this.duoLaunchAction === DuoLaunchAction.SINGLE_ACTION_POPOUT) ||
(this.selectedProviderType === TwoFactorProviderType.WebAuthn && this.webAuthInNewTab)
);
}
async use2faRecoveryCode() {
// TODO: PM-17696 eventually we should have a consolidated recover-2fa component as a follow up
// so that we don't have to always open a new tab for non-web clients.
const env = await firstValueFrom(this.environmentService.environment$);
const webVault = env.getWebVaultUrl();
this.platformUtilsService.launchUri(webVault + "/#/recover-2fa");
}
async handleEnterKeyPress() {
// Each 2FA provider has a different implementation.
// For example, email 2FA uses an input of type "text" for the token which does not automatically submit on enter.
// Yubikey, however, uses an input with type "password" which does automatically submit on enter.
// So we have to handle the enter key press differently for each provider.
switch (this.selectedProviderType) {
case TwoFactorProviderType.Authenticator:
case TwoFactorProviderType.Email:
// We must actually submit the form via click in order for the tokenFormControl value to be set.
this.continueButton?.nativeElement?.click();
break;
case TwoFactorProviderType.Duo:
case TwoFactorProviderType.OrganizationDuo:
case TwoFactorProviderType.WebAuthn:
case TwoFactorProviderType.Yubikey:
// Do nothing
break;
default:
this.logService.error(
"handleEnterKeyPress: Unhandled 2FA provider type",
this.selectedProviderType,
);
break;
}
}
async ngOnDestroy() {
this.twoFactorAuthComponentService.removePopupWidthExtension?.();
}
}

View File

@@ -0,0 +1,74 @@
import { Component } from "@angular/core";
import { TestBed } from "@angular/core/testing";
import { provideRouter, Router } from "@angular/router";
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject } from "rxjs";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { AuthenticationType } from "@bitwarden/common/auth/enums/authentication-type";
import { LoginStrategyServiceAbstraction } from "../../common";
import { TwoFactorAuthGuard } from "./two-factor-auth.guard";
@Component({ template: "" })
export class EmptyComponent {}
describe("TwoFactorAuthGuard", () => {
let loginStrategyService: MockProxy<LoginStrategyServiceAbstraction>;
const currentAuthTypesSubject = new BehaviorSubject<AuthenticationType | null>(null);
let twoFactorService: MockProxy<TwoFactorService>;
let router: Router;
beforeEach(() => {
loginStrategyService = mock<LoginStrategyServiceAbstraction>();
loginStrategyService.currentAuthType$ = currentAuthTypesSubject.asObservable();
twoFactorService = mock<TwoFactorService>();
TestBed.configureTestingModule({
providers: [
provideRouter([
{ path: "login", component: EmptyComponent },
{ path: "protected", component: EmptyComponent, canActivate: [TwoFactorAuthGuard] },
]),
{ provide: LoginStrategyServiceAbstraction, useValue: loginStrategyService },
{ provide: TwoFactorService, useValue: twoFactorService },
],
});
router = TestBed.inject(Router);
});
it("should redirect to /login if the user is not authenticating", async () => {
// Arrange
currentAuthTypesSubject.next(null);
twoFactorService.getProviders.mockResolvedValue(null);
// Act
await router.navigateByUrl("/protected");
// Assert
expect(router.url).toBe("/login");
});
const authenticationTypes = Object.entries(AuthenticationType)
// filter out reverse mappings (e.g., "0": "Password")
.filter(([key, value]) => typeof value === "number")
.map(([key, value]) => [value, key]) as [AuthenticationType, string][];
authenticationTypes.forEach(([authType, authTypeName]) => {
it(`should redirect to /login if the user is authenticating with ${authTypeName} but no two-factor providers exist`, async () => {
// Arrange
currentAuthTypesSubject.next(authType);
twoFactorService.getProviders.mockResolvedValue(null);
// Act
await router.navigateByUrl("/protected");
// Assert
expect(router.url).toBe("/login");
});
});
});

View File

@@ -0,0 +1,33 @@
import { inject } from "@angular/core";
import {
ActivatedRouteSnapshot,
CanActivateFn,
Router,
RouterStateSnapshot,
UrlTree,
} from "@angular/router";
import { firstValueFrom } from "rxjs";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { LoginStrategyServiceAbstraction } from "../../common";
export const TwoFactorAuthGuard: CanActivateFn = async (
route: ActivatedRouteSnapshot,
routerState: RouterStateSnapshot,
): Promise<boolean | UrlTree> => {
const loginStrategyService = inject(LoginStrategyServiceAbstraction);
const twoFactorService = inject(TwoFactorService);
const router = inject(Router);
const currentAuthType = await firstValueFrom(loginStrategyService.currentAuthType$);
const userIsAuthenticating = currentAuthType !== null;
const twoFactorProviders = await twoFactorService.getProviders();
if (!userIsAuthenticating || twoFactorProviders == null) {
return router.createUrlTree(["/login"]);
}
return true;
};

View File

@@ -0,0 +1,50 @@
<bit-dialog [background]="'alt'" dialogSize="large">
<span bitDialogTitle>
{{ "selectTwoStepLoginMethod" | i18n }}
</span>
<ng-container bitDialogContent>
<bit-item-group>
<bit-item *ngFor="let provider of providers" (click)="choose(provider)">
<button bit-item-content [truncate]="false" type="button" class="tw-h-auto md:tw-h-20">
<div
slot="start"
[ngSwitch]="provider.type"
class="tw-w-16 md:tw-w-20 tw-mr-2 sm:tw-mr-4"
>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.Authenticator"
[icon]="Icons.TwoFactorAuthAuthenticatorIcon"
></bit-icon>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.Email"
[icon]="Icons.TwoFactorAuthEmailIcon"
></bit-icon>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.Duo"
[icon]="Icons.TwoFactorAuthDuoIcon"
></bit-icon>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.Yubikey"
[icon]="Icons.TwoFactorAuthYubicoIcon"
></bit-icon>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.OrganizationDuo"
[icon]="Icons.TwoFactorAuthDuoIcon"
></bit-icon>
<bit-icon
*ngSwitchCase="TwoFactorProviderType.WebAuthn"
[icon]="Icons.TwoFactorAuthWebAuthnIcon"
></bit-icon>
</div>
{{ provider.name }}
<ng-container slot="secondary"> {{ provider.description }} </ng-container>
</button>
</bit-item>
</bit-item-group>
</ng-container>
<ng-container bitDialogFooter>
<button bitButton type="button" buttonType="secondary" (click)="cancel()">
{{ "cancel" | i18n }}
</button>
</ng-container>
</bit-dialog>

View File

@@ -0,0 +1,81 @@
import { DialogRef } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, OnInit } from "@angular/core";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import {
TwoFactorProviderDetails,
TwoFactorService,
} from "@bitwarden/common/auth/abstractions/two-factor.service";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import {
ButtonModule,
DialogModule,
DialogService,
IconModule,
ItemModule,
TypographyModule,
} from "@bitwarden/components";
import {
TwoFactorAuthAuthenticatorIcon,
TwoFactorAuthDuoIcon,
TwoFactorAuthEmailIcon,
TwoFactorAuthWebAuthnIcon,
TwoFactorAuthYubicoIcon,
} from "../icons/two-factor-auth";
export type TwoFactorOptionsDialogResult = {
type: TwoFactorProviderType;
};
@Component({
standalone: true,
selector: "app-two-factor-options",
templateUrl: "two-factor-options.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
TypographyModule,
ItemModule,
IconModule,
],
providers: [],
})
export class TwoFactorOptionsComponent implements OnInit {
providers: TwoFactorProviderDetails[] = [];
TwoFactorProviderType = TwoFactorProviderType;
readonly Icons = {
TwoFactorAuthAuthenticatorIcon,
TwoFactorAuthEmailIcon,
TwoFactorAuthDuoIcon,
TwoFactorAuthYubicoIcon,
TwoFactorAuthWebAuthnIcon,
};
constructor(
private twoFactorService: TwoFactorService,
private dialogRef: DialogRef,
) {}
async ngOnInit() {
const providers = await this.twoFactorService.getSupportedProviders(window);
providers.sort((a: TwoFactorProviderDetails, b: TwoFactorProviderDetails) => a.sort - b.sort);
this.providers = providers;
}
async choose(p: TwoFactorProviderDetails) {
this.dialogRef.close({ type: p.type });
}
static open(dialogService: DialogService) {
return dialogService.open<TwoFactorOptionsDialogResult>(TwoFactorOptionsComponent);
}
cancel() {
this.dialogRef.close();
}
}