1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-21 10:43:35 +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

@@ -885,6 +885,21 @@
"logInToBitwarden": {
"message": "Log in to Bitwarden"
},
"enterTheCodeSentToYourEmail": {
"message": "Enter the code sent to your email"
},
"enterTheCodeFromYourAuthenticatorApp": {
"message": "Enter the code from your authenticator app"
},
"pressYourYubiKeyToAuthenticate": {
"message": "Press your YubiKey to authenticate"
},
"duoTwoFactorRequiredPageSubtitle": {
"message": "Duo two-step login is required for your account. Follow the steps below to finish logging in."
},
"followTheStepsBelowToFinishLoggingIn": {
"message": "Follow the steps below to finish logging in."
},
"restartRegistration": {
"message": "Restart registration"
},
@@ -1374,12 +1389,22 @@
"rememberMe": {
"message": "Remember me"
},
"dontAskAgainOnThisDeviceFor30Days": {
"message": "Don't ask again on this device for 30 days"
},
"sendVerificationCodeEmailAgain": {
"message": "Send verification code email again"
},
"useAnotherTwoStepMethod": {
"message": "Use another two-step login method"
},
"selectAnotherMethod": {
"message": "Select another method",
"description": "Select another two-step login method"
},
"useYourRecoveryCode": {
"message": "Use your recovery code"
},
"insertYubiKey": {
"message": "Insert your YubiKey into your computer's USB port, then touch its button."
},
@@ -1392,9 +1417,18 @@
"webAuthnNewTabOpen": {
"message": "Open new tab"
},
"openInNewTab": {
"message": "Open in new tab"
},
"webAuthnAuthenticate": {
"message": "Authenticate WebAuthn"
},
"readSecurityKey": {
"message": "Read security key"
},
"awaitingSecurityKeyInteraction": {
"message": "Awaiting security key interaction..."
},
"loginUnavailable": {
"message": "Login unavailable"
},
@@ -1407,6 +1441,9 @@
"twoStepOptions": {
"message": "Two-step login options"
},
"selectTwoStepLoginMethod": {
"message": "Select two-step login method"
},
"recoveryCodeDesc": {
"message": "Lost access to all of your two-factor providers? Use your recovery code to turn off all two-factor providers from your account."
},

View File

@@ -1,118 +0,0 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, OnDestroy, OnInit } from "@angular/core";
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { Subject, Subscription, filter, firstValueFrom, takeUntil } from "rxjs";
import { TwoFactorAuthDuoComponent as TwoFactorAuthDuoBaseComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth-duo.component";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { ToastService } from "@bitwarden/components";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { AsyncActionsModule } from "../../../../../libs/components/src/async-actions";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { ButtonModule } from "../../../../../libs/components/src/button";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { FormFieldModule } from "../../../../../libs/components/src/form-field";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { LinkModule } from "../../../../../libs/components/src/link";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { TypographyModule } from "../../../../../libs/components/src/typography";
import { ZonedMessageListenerService } from "../../platform/browser/zoned-message-listener.service";
@Component({
standalone: true,
selector: "app-two-factor-auth-duo",
templateUrl:
"../../../../../libs/angular/src/auth/components/two-factor-auth/two-factor-auth-duo.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
})
export class TwoFactorAuthDuoComponent
extends TwoFactorAuthDuoBaseComponent
implements OnInit, OnDestroy
{
private destroy$ = new Subject<void>();
duoResultSubscription: Subscription;
constructor(
protected i18nService: I18nService,
protected platformUtilsService: PlatformUtilsService,
private browserMessagingApi: ZonedMessageListenerService,
private environmentService: EnvironmentService,
toastService: ToastService,
) {
super(i18nService, platformUtilsService, toastService);
}
async ngOnInit(): Promise<void> {
await super.ngOnInit();
}
async ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
protected override setupDuoResultListener() {
if (!this.duoResultSubscription) {
this.duoResultSubscription = this.browserMessagingApi
.messageListener$()
.pipe(
filter((msg: any) => msg.command === "duoResult"),
takeUntil(this.destroy$),
)
.subscribe((msg: { command: string; code: string; state: string }) => {
this.token.emit(msg.code + "|" + msg.state);
});
}
}
override async launchDuoFrameless() {
if (this.duoFramelessUrl === null) {
this.toastService.showToast({
variant: "error",
title: null,
message: this.i18nService.t("duoHealthCheckResultsInNullAuthUrlError"),
});
return;
}
const duoHandOffMessage = {
title: this.i18nService.t("youSuccessfullyLoggedIn"),
message: this.i18nService.t("youMayCloseThisWindow"),
isCountdown: false,
};
// we're using the connector here as a way to set a cookie with translations
// before continuing to the duo frameless url
const env = await firstValueFrom(this.environmentService.environment$);
const launchUrl =
env.getWebVaultUrl() +
"/duo-redirect-connector.html" +
"?duoFramelessUrl=" +
encodeURIComponent(this.duoFramelessUrl) +
"&handOffMessage=" +
encodeURIComponent(JSON.stringify(duoHandOffMessage));
this.platformUtilsService.launchUri(launchUrl);
}
}

View File

@@ -1,65 +0,0 @@
import { DialogModule } from "@angular/cdk/dialog";
import { CommonModule } from "@angular/common";
import { Component, OnInit, inject } from "@angular/core";
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { TwoFactorAuthEmailComponent as TwoFactorAuthEmailBaseComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth-email.component";
import { JslibModule } from "@bitwarden/angular/jslib.module";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { AsyncActionsModule } from "../../../../../libs/components/src/async-actions";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { ButtonModule } from "../../../../../libs/components/src/button";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { DialogService } from "../../../../../libs/components/src/dialog";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { FormFieldModule } from "../../../../../libs/components/src/form-field";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { LinkModule } from "../../../../../libs/components/src/link";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import { TypographyModule } from "../../../../../libs/components/src/typography";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
@Component({
standalone: true,
selector: "app-two-factor-auth-email",
templateUrl:
"../../../../../libs/angular/src/auth/components/two-factor-auth/two-factor-auth-email.component.html",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
FormsModule,
],
})
export class TwoFactorAuthEmailComponent extends TwoFactorAuthEmailBaseComponent implements OnInit {
private dialogService = inject(DialogService);
async ngOnInit(): Promise<void> {
if (BrowserPopupUtils.inPopup(window)) {
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "warning" },
content: { key: "popup2faCloseMessage" },
type: "warning",
});
if (confirmed) {
await BrowserPopupUtils.openCurrentPagePopout(window);
return;
}
}
await super.ngOnInit();
}
}

View File

@@ -1,170 +0,0 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { CommonModule } from "@angular/common";
import { Component, Inject, OnDestroy, OnInit } from "@angular/core";
import { FormBuilder, ReactiveFormsModule } from "@angular/forms";
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { TwoFactorAuthAuthenticatorComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth-authenticator.component";
import { TwoFactorAuthWebAuthnComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth-webauthn.component";
import { TwoFactorAuthYubikeyComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth-yubikey.component";
import { TwoFactorAuthComponent as BaseTwoFactorAuthComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-auth.component";
import { TwoFactorOptionsComponent } from "@bitwarden/angular/auth/components/two-factor-auth/two-factor-options.component";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
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 { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.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 { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { SyncService } from "@bitwarden/common/platform/sync";
import {
ButtonModule,
FormFieldModule,
AsyncActionsModule,
CheckboxModule,
DialogModule,
LinkModule,
TypographyModule,
DialogService,
ToastService,
} from "@bitwarden/components";
// FIXME: remove `src` and fix import
// eslint-disable-next-line no-restricted-imports
import {
LoginStrategyServiceAbstraction,
LoginEmailServiceAbstraction,
UserDecryptionOptionsServiceAbstraction,
} from "../../../../../libs/auth/src/common/abstractions";
import { BrowserApi } from "../../platform/browser/browser-api";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
import { TwoFactorAuthDuoComponent } from "./two-factor-auth-duo.component";
import { TwoFactorAuthEmailComponent } from "./two-factor-auth-email.component";
@Component({
standalone: true,
templateUrl:
"../../../../../libs/angular/src/auth/components/two-factor-auth/two-factor-auth.component.html",
selector: "app-two-factor-auth",
imports: [
CommonModule,
JslibModule,
DialogModule,
ButtonModule,
LinkModule,
TypographyModule,
ReactiveFormsModule,
FormFieldModule,
AsyncActionsModule,
RouterLink,
CheckboxModule,
TwoFactorOptionsComponent,
TwoFactorAuthEmailComponent,
TwoFactorAuthAuthenticatorComponent,
TwoFactorAuthYubikeyComponent,
TwoFactorAuthDuoComponent,
TwoFactorAuthWebAuthnComponent,
],
providers: [I18nPipe],
})
export class TwoFactorAuthComponent
extends BaseTwoFactorAuthComponent
implements OnInit, OnDestroy
{
constructor(
protected loginStrategyService: LoginStrategyServiceAbstraction,
protected router: Router,
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
environmentService: EnvironmentService,
dialogService: DialogService,
protected route: ActivatedRoute,
logService: LogService,
protected twoFactorService: TwoFactorService,
loginEmailService: LoginEmailServiceAbstraction,
userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction,
protected ssoLoginService: SsoLoginServiceAbstraction,
protected configService: ConfigService,
masterPasswordService: InternalMasterPasswordServiceAbstraction,
accountService: AccountService,
formBuilder: FormBuilder,
@Inject(WINDOW) protected win: Window,
private syncService: SyncService,
private messagingService: MessagingService,
toastService: ToastService,
) {
super(
loginStrategyService,
router,
i18nService,
platformUtilsService,
environmentService,
dialogService,
route,
logService,
twoFactorService,
loginEmailService,
userDecryptionOptionsService,
ssoLoginService,
configService,
masterPasswordService,
accountService,
formBuilder,
win,
toastService,
);
this.onSuccessfulLoginTdeNavigate = async () => {
this.win.close();
};
this.onSuccessfulLoginNavigate = this.goAfterLogIn;
}
async ngOnInit(): Promise<void> {
await super.ngOnInit();
if (this.route.snapshot.paramMap.has("webAuthnResponse")) {
// WebAuthn fallback response
this.selectedProviderType = TwoFactorProviderType.WebAuthn;
this.token = this.route.snapshot.paramMap.get("webAuthnResponse");
this.onSuccessfulLogin = async () => {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.syncService.fullSync(true);
this.messagingService.send("reloadPopup");
window.close();
};
this.remember = this.route.snapshot.paramMap.get("remember") === "true";
await this.submit();
return;
}
if (await BrowserPopupUtils.inPopout(this.win)) {
this.selectedProviderType = TwoFactorProviderType.Email;
}
// WebAuthn prompt appears inside the popup on linux, and requires a larger popup width
// than usual to avoid cutting off the dialog.
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && (await this.isLinux())) {
document.body.classList.add("linux-webauthn");
}
}
async ngOnDestroy() {
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && (await this.isLinux())) {
document.body.classList.remove("linux-webauthn");
}
}
async isLinux() {
return (await BrowserApi.getPlatformInfo()).os === "linux";
}
}

View File

@@ -1,7 +1,7 @@
import { Component } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { TwoFactorOptionsComponent as BaseTwoFactorOptionsComponent } from "@bitwarden/angular/auth/components/two-factor-options.component";
import { TwoFactorOptionsComponentV1 as BaseTwoFactorOptionsComponent } from "@bitwarden/angular/auth/components/two-factor-options-v1.component";
import {
TwoFactorProviderDetails,
TwoFactorService,
@@ -12,9 +12,9 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
@Component({
selector: "app-two-factor-options",
templateUrl: "two-factor-options.component.html",
templateUrl: "two-factor-options-v1.component.html",
})
export class TwoFactorOptionsComponent extends BaseTwoFactorOptionsComponent {
export class TwoFactorOptionsComponentV1 extends BaseTwoFactorOptionsComponent {
constructor(
twoFactorService: TwoFactorService,
router: Router,

View File

@@ -5,7 +5,7 @@ import { ActivatedRoute, Router } from "@angular/router";
import { Subject, Subscription, firstValueFrom } from "rxjs";
import { filter, first, takeUntil } from "rxjs/operators";
import { TwoFactorComponent as BaseTwoFactorComponent } from "@bitwarden/angular/auth/components/two-factor.component";
import { TwoFactorComponentV1 as BaseTwoFactorComponent } from "@bitwarden/angular/auth/components/two-factor-v1.component";
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
import {
LoginStrategyServiceAbstraction,
@@ -37,9 +37,9 @@ import { closeTwoFactorAuthWebAuthnPopout } from "./utils/auth-popout-window";
@Component({
selector: "app-two-factor",
templateUrl: "two-factor.component.html",
templateUrl: "two-factor-v1.component.html",
})
export class TwoFactorComponent extends BaseTwoFactorComponent implements OnInit, OnDestroy {
export class TwoFactorComponentV1 extends BaseTwoFactorComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
inPopout = BrowserPopupUtils.inPopout(window);

View File

@@ -10,6 +10,10 @@ import {
openTwoFactorAuthWebAuthnPopout,
closeTwoFactorAuthWebAuthnPopout,
closeSsoAuthResultPopout,
openTwoFactorAuthEmailPopout,
closeTwoFactorAuthEmailPopout,
openTwoFactorAuthDuoPopout,
closeTwoFactorAuthDuoPopout,
} from "./auth-popout-window";
describe("AuthPopoutWindow", () => {
@@ -124,4 +128,40 @@ describe("AuthPopoutWindow", () => {
expect(closeSingleActionPopoutSpy).toHaveBeenCalledWith(AuthPopoutType.twoFactorAuthWebAuthn);
});
});
describe("openTwoFactorAuthEmailPopout", () => {
it("opens a window that facilitates two factor authentication via email", async () => {
await openTwoFactorAuthEmailPopout();
expect(openPopoutSpy).toHaveBeenCalledWith("popup/index.html#/2fa", {
singleActionKey: AuthPopoutType.twoFactorAuthEmail,
});
});
});
describe("closeTwoFactorAuthEmailPopout", () => {
it("closes the two-factor authentication email window", async () => {
await closeTwoFactorAuthEmailPopout();
expect(closeSingleActionPopoutSpy).toHaveBeenCalledWith(AuthPopoutType.twoFactorAuthEmail);
});
});
describe("openTwoFactorAuthDuoPopout", () => {
it("opens a window that facilitates two factor authentication via Duo", async () => {
await openTwoFactorAuthDuoPopout();
expect(openPopoutSpy).toHaveBeenCalledWith("popup/index.html#/2fa", {
singleActionKey: AuthPopoutType.twoFactorAuthDuo,
});
});
});
describe("closeTwoFactorAuthDuoPopout", () => {
it("closes the two-factor authentication Duo window", async () => {
await closeTwoFactorAuthDuoPopout();
expect(closeSingleActionPopoutSpy).toHaveBeenCalledWith(AuthPopoutType.twoFactorAuthDuo);
});
});
});

View File

@@ -7,7 +7,10 @@ const AuthPopoutType = {
unlockExtension: "auth_unlockExtension",
ssoAuthResult: "auth_ssoAuthResult",
twoFactorAuthWebAuthn: "auth_twoFactorAuthWebAuthn",
twoFactorAuthEmail: "auth_twoFactorAuthEmail",
twoFactorAuthDuo: "auth_twoFactorAuthDuo",
} as const;
const extensionUnlockUrls = new Set([
chrome.runtime.getURL("popup/index.html#/lock"),
chrome.runtime.getURL("popup/index.html#/home"),
@@ -87,12 +90,44 @@ async function openTwoFactorAuthWebAuthnPopout(twoFactorAuthWebAuthnData: {
}
/**
* Closes the two-factor authentication popout window.
* Closes the two-factor authentication WebAuthn popout window.
*/
async function closeTwoFactorAuthWebAuthnPopout() {
await BrowserPopupUtils.closeSingleActionPopout(AuthPopoutType.twoFactorAuthWebAuthn);
}
/**
* Opens a popout that facilitates two-factor authentication via email.
*/
async function openTwoFactorAuthEmailPopout() {
await BrowserPopupUtils.openPopout("popup/index.html#/2fa", {
singleActionKey: AuthPopoutType.twoFactorAuthEmail,
});
}
/**
* Closes the two-factor authentication email popout window.
*/
async function closeTwoFactorAuthEmailPopout() {
await BrowserPopupUtils.closeSingleActionPopout(AuthPopoutType.twoFactorAuthEmail);
}
/**
* Opens the two-factor authentication Duo popout.
*/
async function openTwoFactorAuthDuoPopout() {
await BrowserPopupUtils.openPopout("popup/index.html#/2fa", {
singleActionKey: AuthPopoutType.twoFactorAuthDuo,
});
}
/**
* Closes the two-factor authentication Duo popout.
*/
async function closeTwoFactorAuthDuoPopout() {
await BrowserPopupUtils.closeSingleActionPopout(AuthPopoutType.twoFactorAuthDuo);
}
export {
AuthPopoutType,
openUnlockPopout,
@@ -101,4 +136,8 @@ export {
closeSsoAuthResultPopout,
openTwoFactorAuthWebAuthnPopout,
closeTwoFactorAuthWebAuthnPopout,
openTwoFactorAuthEmailPopout,
closeTwoFactorAuthEmailPopout,
openTwoFactorAuthDuoPopout,
closeTwoFactorAuthDuoPopout,
};

View File

@@ -0,0 +1,189 @@
import { MockProxy, mock } from "jest-mock-extended";
// Must mock modules before importing
jest.mock("../popup/utils/auth-popout-window", () => {
const originalModule = jest.requireActual("../popup/utils/auth-popout-window");
return {
...originalModule, // avoid losing the original module's exports
closeSsoAuthResultPopout: jest.fn(),
closeTwoFactorAuthWebAuthnPopout: jest.fn(),
closeTwoFactorAuthEmailPopout: jest.fn(),
closeTwoFactorAuthDuoPopout: jest.fn(),
};
});
jest.mock("../../platform/popup/browser-popup-utils", () => ({
inSingleActionPopout: jest.fn(),
}));
import { DuoLaunchAction } from "@bitwarden/auth/angular";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { BrowserApi } from "../../platform/browser/browser-api";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
import {
AuthPopoutType,
closeSsoAuthResultPopout,
closeTwoFactorAuthDuoPopout,
closeTwoFactorAuthEmailPopout,
closeTwoFactorAuthWebAuthnPopout,
} from "../popup/utils/auth-popout-window";
import { ExtensionTwoFactorAuthComponentService } from "./extension-two-factor-auth-component.service";
describe("ExtensionTwoFactorAuthComponentService", () => {
let extensionTwoFactorAuthComponentService: ExtensionTwoFactorAuthComponentService;
let window: MockProxy<Window>;
beforeEach(() => {
jest.clearAllMocks();
window = mock<Window>();
document.body.className = ""; // Reset any added classes between tests.
extensionTwoFactorAuthComponentService = new ExtensionTwoFactorAuthComponentService(window);
});
describe("shouldCheckForWebAuthnQueryParamResponse", () => {
it("should return true for the extension", () => {
expect(
extensionTwoFactorAuthComponentService.shouldCheckForWebAuthnQueryParamResponse(),
).toBe(true);
});
});
describe("extendPopupWidthIfRequired", () => {
it("should add linux-webauthn class to body if selected2faProviderType is WebAuthn and isLinux is true", async () => {
jest
.spyOn(extensionTwoFactorAuthComponentService as unknown as any, "isLinux")
.mockResolvedValue(true);
await extensionTwoFactorAuthComponentService.extendPopupWidthIfRequired(
TwoFactorProviderType.WebAuthn,
);
expect(document.body.classList).toContain("linux-webauthn");
});
it("should not add linux-webauthn class to body if selected2faProviderType is WebAuthn and isLinux is false", async () => {
jest
.spyOn(extensionTwoFactorAuthComponentService as unknown as any, "isLinux")
.mockResolvedValue(false);
await extensionTwoFactorAuthComponentService.extendPopupWidthIfRequired(
TwoFactorProviderType.WebAuthn,
);
expect(document.body.classList).not.toContain("linux-webauthn");
});
it.each([
[true, TwoFactorProviderType.Email],
[false, TwoFactorProviderType.Email],
])(
"should not add linux-webauthn class to body if selected2faProviderType is not WebAuthn and isLinux is %s",
async (isLinux, selected2faProviderType) => {
jest
.spyOn(extensionTwoFactorAuthComponentService as unknown as any, "isLinux")
.mockResolvedValue(isLinux);
await extensionTwoFactorAuthComponentService.extendPopupWidthIfRequired(
selected2faProviderType,
);
expect(document.body.classList).not.toContain("linux-webauthn");
},
);
});
describe("removePopupWidthExtension", () => {
it("should remove linux-webauthn class from body", () => {
document.body.classList.add("linux-webauthn");
extensionTwoFactorAuthComponentService.removePopupWidthExtension();
expect(document.body.classList).not.toContain("linux-webauthn");
});
});
describe("closeSingleActionPopouts", () => {
it("should call closeSsoAuthResultPopout if in SSO auth result popout", async () => {
const inSingleActionPopoutSpy = jest
.spyOn(BrowserPopupUtils, "inSingleActionPopout")
.mockImplementation((_, key) => {
return key === AuthPopoutType.ssoAuthResult;
});
await extensionTwoFactorAuthComponentService.closeSingleActionPopouts();
expect(inSingleActionPopoutSpy).toHaveBeenCalledTimes(1);
expect(closeSsoAuthResultPopout).toHaveBeenCalled();
});
it("should call closeTwoFactorAuthWebAuthnPopout if in two factor auth webauthn popout", async () => {
const inSingleActionPopoutSpy = jest
.spyOn(BrowserPopupUtils, "inSingleActionPopout")
.mockImplementation((_, key) => {
return key === AuthPopoutType.twoFactorAuthWebAuthn;
});
await extensionTwoFactorAuthComponentService.closeSingleActionPopouts();
expect(inSingleActionPopoutSpy).toHaveBeenCalledTimes(2);
expect(closeTwoFactorAuthWebAuthnPopout).toHaveBeenCalled();
});
it("should call closeTwoFactorAuthEmailPopout if in two factor auth email popout", async () => {
const inSingleActionPopoutSpy = jest
.spyOn(BrowserPopupUtils, "inSingleActionPopout")
.mockImplementation((_, key) => {
return key === AuthPopoutType.twoFactorAuthEmail;
});
await extensionTwoFactorAuthComponentService.closeSingleActionPopouts();
expect(inSingleActionPopoutSpy).toHaveBeenCalledTimes(3);
expect(closeTwoFactorAuthEmailPopout).toHaveBeenCalled();
});
it("should call closeTwoFactorAuthDuoPopout if in two factor auth duo popout", async () => {
const inSingleActionPopoutSpy = jest
.spyOn(BrowserPopupUtils, "inSingleActionPopout")
.mockImplementation((_, key) => {
return key === AuthPopoutType.twoFactorAuthDuo;
});
await extensionTwoFactorAuthComponentService.closeSingleActionPopouts();
expect(inSingleActionPopoutSpy).toHaveBeenCalledTimes(4);
expect(closeTwoFactorAuthDuoPopout).toHaveBeenCalled();
});
});
describe("reloadOpenWindows", () => {
it("should call reload open windows (exempting current)", async () => {
const reloadOpenWindowsSpy = jest.spyOn(BrowserApi, "reloadOpenWindows").mockImplementation();
extensionTwoFactorAuthComponentService.reloadOpenWindows();
expect(reloadOpenWindowsSpy).toHaveBeenCalledWith(true);
});
});
describe("determineDuoLaunchAction", () => {
it("should return DIRECT_LAUNCH if in two factor auth duo popout", () => {
jest.spyOn(BrowserPopupUtils, "inSingleActionPopout").mockImplementation((_, key) => {
return key === AuthPopoutType.twoFactorAuthDuo;
});
expect(extensionTwoFactorAuthComponentService.determineDuoLaunchAction()).toBe(
DuoLaunchAction.DIRECT_LAUNCH,
);
});
it("should return SINGLE_ACTION_POPOUT if not in two factor auth duo popout", () => {
jest.spyOn(BrowserPopupUtils, "inSingleActionPopout").mockImplementation(() => false);
expect(extensionTwoFactorAuthComponentService.determineDuoLaunchAction()).toBe(
DuoLaunchAction.SINGLE_ACTION_POPOUT,
);
});
});
});

View File

@@ -0,0 +1,115 @@
import {
DefaultTwoFactorAuthComponentService,
DuoLaunchAction,
TwoFactorAuthComponentService,
} from "@bitwarden/auth/angular";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { BrowserApi } from "../../platform/browser/browser-api";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
import {
AuthPopoutType,
closeSsoAuthResultPopout,
closeTwoFactorAuthDuoPopout,
closeTwoFactorAuthEmailPopout,
closeTwoFactorAuthWebAuthnPopout,
} from "../popup/utils/auth-popout-window";
export class ExtensionTwoFactorAuthComponentService
extends DefaultTwoFactorAuthComponentService
implements TwoFactorAuthComponentService
{
constructor(private window: Window) {
super();
}
shouldCheckForWebAuthnQueryParamResponse(): boolean {
return true;
}
async extendPopupWidthIfRequired(selected2faProviderType: TwoFactorProviderType): Promise<void> {
// WebAuthn prompt appears inside the popup on linux, and requires a larger popup width
// than usual to avoid cutting off the dialog.
const isLinux = await this.isLinux();
if (selected2faProviderType === TwoFactorProviderType.WebAuthn && isLinux) {
document.body.classList.add("linux-webauthn");
}
}
removePopupWidthExtension(): void {
document.body.classList.remove("linux-webauthn");
}
reloadOpenWindows(): void {
// Force sidebars (FF && Opera) to reload while exempting current window
// because we are just going to close the current window if it is in a popout
// or navigate forward if it is in the popup
BrowserApi.reloadOpenWindows(true);
}
async closeSingleActionPopouts(): Promise<boolean> {
// If we are in a single action popout, we don't need the popout anymore because the intent
// is for the user to be left on the web vault screen which tells them to continue in
// the browser extension (sidebar or popup). We don't want the user to be left with a
// floating, popped out extension which could be lost behind another window or minimized.
// Currently, the popped out window thinks it is active and wouldn't time out which
// leads to the security concern. So, we close the popped out extension to avoid this.
const inSsoAuthResultPopout = BrowserPopupUtils.inSingleActionPopout(
this.window,
AuthPopoutType.ssoAuthResult,
);
if (inSsoAuthResultPopout) {
await closeSsoAuthResultPopout();
return true;
}
const inTwoFactorAuthWebAuthnPopout = BrowserPopupUtils.inSingleActionPopout(
this.window,
AuthPopoutType.twoFactorAuthWebAuthn,
);
if (inTwoFactorAuthWebAuthnPopout) {
await closeTwoFactorAuthWebAuthnPopout();
return true;
}
const inTwoFactorAuthEmailPopout = BrowserPopupUtils.inSingleActionPopout(
this.window,
AuthPopoutType.twoFactorAuthEmail,
);
if (inTwoFactorAuthEmailPopout) {
await closeTwoFactorAuthEmailPopout();
return true;
}
const inTwoFactorAuthDuoPopout = BrowserPopupUtils.inSingleActionPopout(
this.window,
AuthPopoutType.twoFactorAuthDuo,
);
if (inTwoFactorAuthDuoPopout) {
await closeTwoFactorAuthDuoPopout();
return true;
}
return false;
}
private async isLinux(): Promise<boolean> {
const platformInfo = await BrowserApi.getPlatformInfo();
return platformInfo.os === "linux";
}
determineDuoLaunchAction(): DuoLaunchAction {
const inTwoFactorAuthDuoPopout = BrowserPopupUtils.inSingleActionPopout(
this.window,
AuthPopoutType.twoFactorAuthDuo,
);
if (inTwoFactorAuthDuoPopout) {
return DuoLaunchAction.DIRECT_LAUNCH;
}
return DuoLaunchAction.SINGLE_ACTION_POPOUT;
}
}

View File

@@ -0,0 +1,93 @@
import { MockProxy, mock } from "jest-mock-extended";
import { BehaviorSubject, firstValueFrom } from "rxjs";
import {
Environment,
EnvironmentService,
} from "@bitwarden/common/platform/abstractions/environment.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { ZonedMessageListenerService } from "../../platform/browser/zoned-message-listener.service";
import I18nService from "../../platform/services/i18n.service";
import { ExtensionTwoFactorAuthDuoComponentService } from "./extension-two-factor-auth-duo-component.service";
describe("ExtensionTwoFactorAuthDuoComponentService", () => {
let extensionTwoFactorAuthDuoComponentService: ExtensionTwoFactorAuthDuoComponentService;
let browserMessagingApi: MockProxy<ZonedMessageListenerService>;
let environmentService: MockProxy<EnvironmentService>;
let i18nService: MockProxy<I18nService>;
let platformUtilsService: MockProxy<PlatformUtilsService>;
beforeEach(() => {
jest.clearAllMocks();
browserMessagingApi = mock<ZonedMessageListenerService>();
environmentService = mock<EnvironmentService>();
i18nService = mock<I18nService>();
platformUtilsService = mock<PlatformUtilsService>();
extensionTwoFactorAuthDuoComponentService = new ExtensionTwoFactorAuthDuoComponentService(
browserMessagingApi,
environmentService,
i18nService,
platformUtilsService,
);
});
describe("listenForDuo2faResult$", () => {
it("should return an observable that emits a duo 2FA result when a duo result message is received", async () => {
const message = {
command: "duoResult",
code: "123456",
state: "abcdef",
};
const expectedDuo2faResult = {
code: message.code,
state: message.state,
token: `${message.code}|${message.state}`,
};
const messageStream$ = new BehaviorSubject(message);
browserMessagingApi.messageListener$.mockReturnValue(messageStream$);
const duo2faResult = await firstValueFrom(
extensionTwoFactorAuthDuoComponentService.listenForDuo2faResult$(),
);
expect(duo2faResult).toEqual(expectedDuo2faResult);
});
});
describe("launchDuoFrameless", () => {
it("should launch the duo frameless url", async () => {
// Arrange
const duoFramelessUrl = "https://duoFramelessUrl";
const webVaultUrl = "https://webVaultUrl";
i18nService.t.mockImplementation((key) => key);
const launchUrl = `${webVaultUrl}/duo-redirect-connector.html?duoFramelessUrl=${encodeURIComponent(
duoFramelessUrl,
)}&handOffMessage=${encodeURIComponent(
JSON.stringify({
title: "youSuccessfullyLoggedIn",
message: "youMayCloseThisWindow",
isCountdown: false,
}),
)}`;
const mockEnvironment = {
getWebVaultUrl: () => webVaultUrl,
} as unknown as Environment;
const environmentBSubject = new BehaviorSubject(mockEnvironment);
environmentService.environment$ = environmentBSubject.asObservable();
// Act
await extensionTwoFactorAuthDuoComponentService.launchDuoFrameless(duoFramelessUrl);
// Assert
expect(platformUtilsService.launchUri).toHaveBeenCalledWith(launchUrl);
});
});
});

View File

@@ -0,0 +1,62 @@
import { filter, firstValueFrom, map, Observable } from "rxjs";
import { Duo2faResult, TwoFactorAuthDuoComponentService } from "@bitwarden/auth/angular";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { openTwoFactorAuthDuoPopout } from "../../auth/popup/utils/auth-popout-window";
import { ZonedMessageListenerService } from "../../platform/browser/zoned-message-listener.service";
interface Message {
command: string;
code: string;
state: string;
}
export class ExtensionTwoFactorAuthDuoComponentService implements TwoFactorAuthDuoComponentService {
constructor(
private browserMessagingApi: ZonedMessageListenerService,
private environmentService: EnvironmentService,
private i18nService: I18nService,
private platformUtilsService: PlatformUtilsService,
) {}
listenForDuo2faResult$(): Observable<Duo2faResult> {
return this.browserMessagingApi.messageListener$().pipe(
filter((msg): msg is Message => {
return (msg as Message).command === "duoResult";
}),
map((msg: Message) => {
return {
code: msg.code,
state: msg.state,
token: `${msg.code}|${msg.state}`,
} as Duo2faResult;
}),
);
}
async launchDuoFrameless(duoFramelessUrl: string): Promise<void> {
const duoHandOffMessage = {
title: this.i18nService.t("youSuccessfullyLoggedIn"),
message: this.i18nService.t("youMayCloseThisWindow"),
isCountdown: false,
};
// we're using the connector here as a way to set a cookie with translations
// before continuing to the duo frameless url
const env = await firstValueFrom(this.environmentService.environment$);
const launchUrl =
env.getWebVaultUrl() +
"/duo-redirect-connector.html" +
"?duoFramelessUrl=" +
encodeURIComponent(duoFramelessUrl) +
"&handOffMessage=" +
encodeURIComponent(JSON.stringify(duoHandOffMessage));
this.platformUtilsService.launchUri(launchUrl);
}
async openTwoFactorAuthDuoPopout(): Promise<void> {
await openTwoFactorAuthDuoPopout();
}
}

View File

@@ -0,0 +1,93 @@
import { MockProxy, mock } from "jest-mock-extended";
import { DialogService } from "@bitwarden/components";
// Must mock modules before importing
jest.mock("../popup/utils/auth-popout-window", () => {
const originalModule = jest.requireActual("../popup/utils/auth-popout-window");
return {
...originalModule, // avoid losing the original module's exports
openTwoFactorAuthEmailPopout: jest.fn(),
};
});
jest.mock("../../platform/popup/browser-popup-utils", () => ({
inPopup: jest.fn(),
}));
import { openTwoFactorAuthEmailPopout } from "../../auth/popup/utils/auth-popout-window";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
import { ExtensionTwoFactorAuthEmailComponentService } from "./extension-two-factor-auth-email-component.service";
describe("ExtensionTwoFactorAuthEmailComponentService", () => {
let extensionTwoFactorAuthEmailComponentService: ExtensionTwoFactorAuthEmailComponentService;
let dialogService: MockProxy<DialogService>;
let window: MockProxy<Window>;
beforeEach(() => {
jest.clearAllMocks();
dialogService = mock<DialogService>();
window = mock<Window>();
extensionTwoFactorAuthEmailComponentService = new ExtensionTwoFactorAuthEmailComponentService(
dialogService,
window,
);
});
describe("openPopoutIfApprovedForEmail2fa", () => {
it("should open a popout if the user confirms the warning to popout the extension when in the popup", async () => {
// Arrange
dialogService.openSimpleDialog.mockResolvedValue(true);
jest.spyOn(BrowserPopupUtils, "inPopup").mockReturnValue(true);
// Act
await extensionTwoFactorAuthEmailComponentService.openPopoutIfApprovedForEmail2fa();
// Assert
expect(dialogService.openSimpleDialog).toHaveBeenCalledWith({
title: { key: "warning" },
content: { key: "popup2faCloseMessage" },
type: "warning",
});
expect(openTwoFactorAuthEmailPopout).toHaveBeenCalled();
});
it("should not open a popout if the user cancels the warning to popout the extension when in the popup", async () => {
// Arrange
dialogService.openSimpleDialog.mockResolvedValue(false);
jest.spyOn(BrowserPopupUtils, "inPopup").mockReturnValue(true);
// Act
await extensionTwoFactorAuthEmailComponentService.openPopoutIfApprovedForEmail2fa();
// Assert
expect(dialogService.openSimpleDialog).toHaveBeenCalledWith({
title: { key: "warning" },
content: { key: "popup2faCloseMessage" },
type: "warning",
});
expect(openTwoFactorAuthEmailPopout).not.toHaveBeenCalled();
});
it("should not open a popout if not in the popup", async () => {
// Arrange
jest.spyOn(BrowserPopupUtils, "inPopup").mockReturnValue(false);
// Act
await extensionTwoFactorAuthEmailComponentService.openPopoutIfApprovedForEmail2fa();
// Assert
expect(dialogService.openSimpleDialog).not.toHaveBeenCalled();
expect(openTwoFactorAuthEmailPopout).not.toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,35 @@
import {
DefaultTwoFactorAuthEmailComponentService,
TwoFactorAuthEmailComponentService,
} from "@bitwarden/auth/angular";
import { DialogService } from "@bitwarden/components";
import { openTwoFactorAuthEmailPopout } from "../../auth/popup/utils/auth-popout-window";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
// TODO: popup state persistence should eventually remove the need for this service
export class ExtensionTwoFactorAuthEmailComponentService
extends DefaultTwoFactorAuthEmailComponentService
implements TwoFactorAuthEmailComponentService
{
constructor(
private dialogService: DialogService,
private window: Window,
) {
super();
}
async openPopoutIfApprovedForEmail2fa(): Promise<void> {
if (BrowserPopupUtils.inPopup(this.window)) {
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "warning" },
content: { key: "popup2faCloseMessage" },
type: "warning",
});
if (confirmed) {
await openTwoFactorAuthEmailPopout();
this.window.close();
}
}
}
}

View File

@@ -0,0 +1,44 @@
import { MockProxy, mock } from "jest-mock-extended";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { ExtensionTwoFactorAuthWebAuthnComponentService } from "./extension-two-factor-auth-webauthn-component.service";
describe("ExtensionTwoFactorAuthWebAuthnComponentService", () => {
let extensionTwoFactorAuthWebAuthnComponentService: ExtensionTwoFactorAuthWebAuthnComponentService;
let platformUtilsService: MockProxy<PlatformUtilsService>;
beforeEach(() => {
jest.clearAllMocks();
platformUtilsService = mock<PlatformUtilsService>();
extensionTwoFactorAuthWebAuthnComponentService =
new ExtensionTwoFactorAuthWebAuthnComponentService(platformUtilsService);
});
describe("shouldOpenWebAuthnInNewTab", () => {
it("should return false if the browser is Chrome", () => {
// Arrange
platformUtilsService.isChrome.mockReturnValue(true);
// Act
const result = extensionTwoFactorAuthWebAuthnComponentService.shouldOpenWebAuthnInNewTab();
// Assert
expect(result).toBe(false);
});
it("should return true if the browser is not Chrome", () => {
// Arrange
platformUtilsService.isChrome.mockReturnValue(false);
// Act
const result = extensionTwoFactorAuthWebAuthnComponentService.shouldOpenWebAuthnInNewTab();
// Assert
expect(result).toBe(true);
});
});
});

View File

@@ -0,0 +1,30 @@
import {
DefaultTwoFactorAuthWebAuthnComponentService,
TwoFactorAuthWebAuthnComponentService,
} from "@bitwarden/auth/angular";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
export class ExtensionTwoFactorAuthWebAuthnComponentService
extends DefaultTwoFactorAuthWebAuthnComponentService
implements TwoFactorAuthWebAuthnComponentService
{
constructor(private platformUtilsService: PlatformUtilsService) {
super();
}
/**
* In the browser extension, we open webAuthn in a new web client tab sometimes due to inline
* WebAuthn Iframe's not working in some browsers. We open a 2FA popout upon successful
* completion of WebAuthn submission with query parameters to finish the 2FA process.
* @returns boolean
*/
shouldOpenWebAuthnInNewTab(): boolean {
const isChrome = this.platformUtilsService.isChrome();
if (isChrome) {
// Chrome now supports WebAuthn in the iframe in the extension now.
return false;
}
return true;
}
}

View File

@@ -18,19 +18,16 @@ import {
unauthGuardFn,
} from "@bitwarden/angular/auth/guards";
import { canAccessFeature } from "@bitwarden/angular/platform/guard/feature-flag.guard";
import { twofactorRefactorSwap } from "@bitwarden/angular/utils/two-factor-component-refactor-route-swap";
import { NewDeviceVerificationNoticeGuard } from "@bitwarden/angular/vault/guards";
import {
AnonLayoutWrapperComponent,
AnonLayoutWrapperData,
DevicesIcon,
DeviceVerificationIcon,
LockIcon,
LoginComponent,
LoginDecryptionOptionsComponent,
LoginSecondaryContentComponent,
LoginViaAuthRequestComponent,
NewDeviceVerificationComponent,
PasswordHintComponent,
RegistrationFinishComponent,
RegistrationLockAltIcon,
@@ -41,6 +38,10 @@ import {
SetPasswordJitComponent,
SsoComponent,
TwoFactorTimeoutIcon,
TwoFactorAuthComponent,
TwoFactorAuthGuard,
NewDeviceVerificationComponent,
DeviceVerificationIcon,
UserLockIcon,
VaultIcon,
} from "@bitwarden/auth/angular";
@@ -68,9 +69,8 @@ import { RemovePasswordComponent } from "../auth/popup/remove-password.component
import { SetPasswordComponent } from "../auth/popup/set-password.component";
import { AccountSecurityComponent } from "../auth/popup/settings/account-security.component";
import { SsoComponentV1 } from "../auth/popup/sso-v1.component";
import { TwoFactorAuthComponent } from "../auth/popup/two-factor-auth.component";
import { TwoFactorOptionsComponent } from "../auth/popup/two-factor-options.component";
import { TwoFactorComponent } from "../auth/popup/two-factor.component";
import { TwoFactorOptionsComponentV1 } from "../auth/popup/two-factor-options-v1.component";
import { TwoFactorComponentV1 } from "../auth/popup/two-factor-v1.component";
import { UpdateTempPasswordComponent } from "../auth/popup/update-temp-password.component";
import { Fido2Component } from "../autofill/popup/fido2/fido2.component";
import { AutofillComponent } from "../autofill/popup/settings/autofill.component";
@@ -153,9 +153,9 @@ const routes: Routes = [
canActivate: [fido2AuthGuard],
data: { elevation: 1 } satisfies RouteDataProperties,
},
...twofactorRefactorSwap(
TwoFactorComponent,
AnonLayoutWrapperComponent,
...unauthUiRefreshSwap(
TwoFactorComponentV1,
ExtensionAnonLayoutWrapperComponent,
{
path: "2fa",
canActivate: [unauthGuardFn(unauthRouteOverrides)],
@@ -163,14 +163,20 @@ const routes: Routes = [
},
{
path: "2fa",
canActivate: [unauthGuardFn(unauthRouteOverrides)],
data: { elevation: 1 } satisfies RouteDataProperties,
canActivate: [unauthGuardFn(unauthRouteOverrides), TwoFactorAuthGuard],
children: [
{
path: "",
component: TwoFactorAuthComponent,
},
],
data: {
elevation: 1,
pageTitle: {
key: "verifyIdentity",
},
showBackButton: true,
} satisfies RouteDataProperties & ExtensionAnonLayoutWrapperData,
},
),
{
@@ -198,7 +204,7 @@ const routes: Routes = [
},
{
path: "2fa-options",
component: TwoFactorOptionsComponent,
component: TwoFactorOptionsComponentV1,
canActivate: [unauthGuardFn(unauthRouteOverrides)],
data: { elevation: 1 } satisfies RouteDataProperties,
},

View File

@@ -31,8 +31,8 @@ import { SetPasswordComponent } from "../auth/popup/set-password.component";
import { AccountSecurityComponent } from "../auth/popup/settings/account-security.component";
import { VaultTimeoutInputComponent } from "../auth/popup/settings/vault-timeout-input.component";
import { SsoComponentV1 } from "../auth/popup/sso-v1.component";
import { TwoFactorOptionsComponent } from "../auth/popup/two-factor-options.component";
import { TwoFactorComponent } from "../auth/popup/two-factor.component";
import { TwoFactorOptionsComponentV1 } from "../auth/popup/two-factor-options-v1.component";
import { TwoFactorComponentV1 } from "../auth/popup/two-factor-v1.component";
import { UpdateTempPasswordComponent } from "../auth/popup/update-temp-password.component";
import { AutofillComponent } from "../autofill/popup/settings/autofill.component";
import { NotificationsSettingsComponent } from "../autofill/popup/settings/notifications.component";
@@ -105,8 +105,8 @@ import "../platform/popup/locales";
SetPasswordComponent,
SsoComponentV1,
TabsV2Component,
TwoFactorComponent,
TwoFactorOptionsComponent,
TwoFactorComponentV1,
TwoFactorOptionsComponentV1,
UpdateTempPasswordComponent,
UserVerificationComponent,
VaultTimeoutInputComponent,

View File

@@ -211,15 +211,13 @@ p.lead {
}
#web-authn-frame {
background: url("../images/loading.svg") 0 0 no-repeat;
width: 100%;
height: 310px;
margin-bottom: -10px;
height: 40px;
iframe {
width: 100%;
height: 100%;
border: none;
height: 100%;
width: 100%;
}
}

View File

@@ -19,12 +19,17 @@ import {
SafeInjectionToken,
SECURE_STORAGE,
SYSTEM_THEME_OBSERVABLE,
WINDOW,
} from "@bitwarden/angular/services/injection-tokens";
import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module";
import {
AnonLayoutWrapperDataService,
LoginComponentService,
LoginDecryptionOptionsService,
TwoFactorAuthComponentService,
TwoFactorAuthEmailComponentService,
TwoFactorAuthDuoComponentService,
TwoFactorAuthWebAuthnComponentService,
SsoComponentService,
} from "@bitwarden/auth/angular";
import {
@@ -129,6 +134,10 @@ import { ExtensionAnonLayoutWrapperDataService } from "../../auth/popup/extensio
import { ExtensionLoginComponentService } from "../../auth/popup/login/extension-login-component.service";
import { ExtensionSsoComponentService } from "../../auth/popup/login/extension-sso-component.service";
import { ExtensionLoginDecryptionOptionsService } from "../../auth/popup/login-decryption-options/extension-login-decryption-options.service";
import { ExtensionTwoFactorAuthComponentService } from "../../auth/services/extension-two-factor-auth-component.service";
import { ExtensionTwoFactorAuthDuoComponentService } from "../../auth/services/extension-two-factor-auth-duo-component.service";
import { ExtensionTwoFactorAuthEmailComponentService } from "../../auth/services/extension-two-factor-auth-email-component.service";
import { ExtensionTwoFactorAuthWebAuthnComponentService } from "../../auth/services/extension-two-factor-auth-webauthn-component.service";
import { AutofillService as AutofillServiceAbstraction } from "../../autofill/services/abstractions/autofill.service";
import AutofillService from "../../autofill/services/autofill.service";
import { InlineMenuFieldQualificationService } from "../../autofill/services/inline-menu-field-qualification.service";
@@ -137,6 +146,7 @@ import { ExtensionLockComponentService } from "../../key-management/lock/service
import { BrowserApi } from "../../platform/browser/browser-api";
import { runInsideAngular } from "../../platform/browser/run-inside-angular.operator";
/* eslint-disable no-restricted-imports */
import { ZonedMessageListenerService } from "../../platform/browser/zoned-message-listener.service";
import { ChromeMessageSender } from "../../platform/messaging/chrome-message.sender";
/* eslint-enable no-restricted-imports */
import { OffscreenDocumentService } from "../../platform/offscreen-document/abstractions/offscreen-document";
@@ -531,6 +541,32 @@ const safeProviders: SafeProvider[] = [
useClass: ExtensionLockComponentService,
deps: [],
}),
// TODO: PM-18182 - Refactor component services into lazy loaded modules
safeProvider({
provide: TwoFactorAuthComponentService,
useClass: ExtensionTwoFactorAuthComponentService,
deps: [WINDOW],
}),
safeProvider({
provide: TwoFactorAuthEmailComponentService,
useClass: ExtensionTwoFactorAuthEmailComponentService,
deps: [DialogService, WINDOW],
}),
safeProvider({
provide: TwoFactorAuthWebAuthnComponentService,
useClass: ExtensionTwoFactorAuthWebAuthnComponentService,
deps: [PlatformUtilsService],
}),
safeProvider({
provide: TwoFactorAuthDuoComponentService,
useClass: ExtensionTwoFactorAuthDuoComponentService,
deps: [
ZonedMessageListenerService,
EnvironmentService,
I18nServiceAbstraction,
PlatformUtilsService,
],
}),
safeProvider({
provide: Fido2UserVerificationService,
useClass: Fido2UserVerificationService,