mirror of
https://github.com/bitwarden/browser
synced 2026-01-06 18:43:25 +00:00
[PM-7564] Move 2fa and login strategy service to popup and add state providers to 2fa service (#8820)
* remove 2fa from main.background * remove login strategy service from main.background * move 2fa and login strategy service to popup, init in browser * add state providers to 2fa service - add deserializer helpers * use key definitions for global state * fix calls to 2fa service * remove extra await * add delay to wait for active account emission in popup * add and fix tests * fix cli * really fix cli * remove timeout and wait for active account * verify expected user is active account * fix tests * address feedback
This commit is contained in:
@@ -253,7 +253,7 @@ describe("SsoComponent", () => {
|
||||
describe("2FA scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const authResult = new AuthResult();
|
||||
authResult.twoFactorProviders = new Map([[TwoFactorProviderType.Authenticator, {}]]);
|
||||
authResult.twoFactorProviders = { [TwoFactorProviderType.Authenticator]: {} };
|
||||
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
selectedUserDecryptionOptions.next(mockUserDecryptionOpts.withMasterPassword);
|
||||
|
||||
@@ -2,7 +2,10 @@ import { Directive, EventEmitter, OnInit, Output } from "@angular/core";
|
||||
import { Router } from "@angular/router";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
|
||||
import {
|
||||
TwoFactorProviderDetails,
|
||||
TwoFactorService,
|
||||
} from "@bitwarden/common/auth/abstractions/two-factor.service";
|
||||
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -24,11 +27,11 @@ export class TwoFactorOptionsComponent implements OnInit {
|
||||
protected environmentService: EnvironmentService,
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.providers = this.twoFactorService.getSupportedProviders(this.win);
|
||||
async ngOnInit() {
|
||||
this.providers = await this.twoFactorService.getSupportedProviders(this.win);
|
||||
}
|
||||
|
||||
choose(p: any) {
|
||||
async choose(p: TwoFactorProviderDetails) {
|
||||
this.onProviderSelected.emit(p.type);
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
}
|
||||
|
||||
async ngOnInit() {
|
||||
if (!(await this.authing()) || this.twoFactorService.getProviders() == null) {
|
||||
if (!(await this.authing()) || (await this.twoFactorService.getProviders()) == null) {
|
||||
// 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.router.navigate([this.loginRoute]);
|
||||
@@ -145,7 +145,9 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
);
|
||||
}
|
||||
|
||||
this.selectedProviderType = this.twoFactorService.getDefaultProvider(this.webAuthnSupported);
|
||||
this.selectedProviderType = await this.twoFactorService.getDefaultProvider(
|
||||
this.webAuthnSupported,
|
||||
);
|
||||
await this.init();
|
||||
}
|
||||
|
||||
@@ -162,12 +164,14 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
|
||||
this.cleanupWebAuthn();
|
||||
this.title = (TwoFactorProviders as any)[this.selectedProviderType].name;
|
||||
const providerData = this.twoFactorService.getProviders().get(this.selectedProviderType);
|
||||
const providerData = await this.twoFactorService.getProviders().then((providers) => {
|
||||
return providers.get(this.selectedProviderType);
|
||||
});
|
||||
switch (this.selectedProviderType) {
|
||||
case TwoFactorProviderType.WebAuthn:
|
||||
if (!this.webAuthnNewTab) {
|
||||
setTimeout(() => {
|
||||
this.authWebAuthn();
|
||||
setTimeout(async () => {
|
||||
await this.authWebAuthn();
|
||||
}, 500);
|
||||
}
|
||||
break;
|
||||
@@ -212,7 +216,7 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
break;
|
||||
case TwoFactorProviderType.Email:
|
||||
this.twoFactorEmail = providerData.Email;
|
||||
if (this.twoFactorService.getProviders().size > 1) {
|
||||
if ((await this.twoFactorService.getProviders()).size > 1) {
|
||||
await this.sendEmail(false);
|
||||
}
|
||||
break;
|
||||
@@ -474,8 +478,10 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
this.emailPromise = null;
|
||||
}
|
||||
|
||||
authWebAuthn() {
|
||||
const providerData = this.twoFactorService.getProviders().get(this.selectedProviderType);
|
||||
async authWebAuthn() {
|
||||
const providerData = await this.twoFactorService.getProviders().then((providers) => {
|
||||
return providers.get(this.selectedProviderType);
|
||||
});
|
||||
|
||||
if (!this.webAuthnSupported || this.webAuthn == null) {
|
||||
return;
|
||||
|
||||
@@ -874,7 +874,7 @@ const safeProviders: SafeProvider[] = [
|
||||
safeProvider({
|
||||
provide: TwoFactorServiceAbstraction,
|
||||
useClass: TwoFactorService,
|
||||
deps: [I18nServiceAbstraction, PlatformUtilsServiceAbstraction],
|
||||
deps: [I18nServiceAbstraction, PlatformUtilsServiceAbstraction, GlobalStateProvider],
|
||||
}),
|
||||
safeProvider({
|
||||
provide: FormValidationErrorsServiceAbstraction,
|
||||
|
||||
@@ -86,7 +86,9 @@ describe("AuthRequestLoginStrategy", () => {
|
||||
|
||||
tokenService.getTwoFactorToken.mockResolvedValue(null);
|
||||
appIdService.getAppId.mockResolvedValue(deviceId);
|
||||
tokenService.decodeAccessToken.mockResolvedValue({});
|
||||
tokenService.decodeAccessToken.mockResolvedValue({
|
||||
sub: mockUserId,
|
||||
});
|
||||
|
||||
authRequestLoginStrategy = new AuthRequestLoginStrategy(
|
||||
cache,
|
||||
|
||||
@@ -25,11 +25,7 @@ import { MessagingService } from "@bitwarden/common/platform/abstractions/messag
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import {
|
||||
Account,
|
||||
AccountProfile,
|
||||
AccountKeys,
|
||||
} from "@bitwarden/common/platform/models/domain/account";
|
||||
import { Account, AccountProfile } from "@bitwarden/common/platform/models/domain/account";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
@@ -214,7 +210,6 @@ describe("LoginStrategy", () => {
|
||||
email: email,
|
||||
},
|
||||
},
|
||||
keys: new AccountKeys(),
|
||||
}),
|
||||
);
|
||||
expect(userDecryptionOptionsService.setUserDecryptionOptions).toHaveBeenCalledWith(
|
||||
@@ -223,6 +218,21 @@ describe("LoginStrategy", () => {
|
||||
expect(messagingService.send).toHaveBeenCalledWith("loggedIn");
|
||||
});
|
||||
|
||||
it("throws if active account isn't found after being initialized", async () => {
|
||||
const idTokenResponse = identityTokenResponseFactory();
|
||||
apiService.postIdentityToken.mockResolvedValue(idTokenResponse);
|
||||
|
||||
const mockVaultTimeoutAction = VaultTimeoutAction.Lock;
|
||||
const mockVaultTimeout = 1000;
|
||||
|
||||
stateService.getVaultTimeoutAction.mockResolvedValue(mockVaultTimeoutAction);
|
||||
stateService.getVaultTimeout.mockResolvedValue(mockVaultTimeout);
|
||||
|
||||
accountService.activeAccountSubject.next(null);
|
||||
|
||||
await expect(async () => await passwordLoginStrategy.logIn(credentials)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("builds AuthResult", async () => {
|
||||
const tokenResponse = identityTokenResponseFactory();
|
||||
tokenResponse.forcePasswordReset = true;
|
||||
@@ -306,8 +316,10 @@ describe("LoginStrategy", () => {
|
||||
expect(tokenService.clearTwoFactorToken).toHaveBeenCalled();
|
||||
|
||||
const expected = new AuthResult();
|
||||
expected.twoFactorProviders = new Map<TwoFactorProviderType, { [key: string]: string }>();
|
||||
expected.twoFactorProviders.set(0, null);
|
||||
expected.twoFactorProviders = { 0: null } as Record<
|
||||
TwoFactorProviderType,
|
||||
Record<string, string>
|
||||
>;
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
@@ -336,8 +348,9 @@ describe("LoginStrategy", () => {
|
||||
expect(messagingService.send).not.toHaveBeenCalled();
|
||||
|
||||
const expected = new AuthResult();
|
||||
expected.twoFactorProviders = new Map<TwoFactorProviderType, { [key: string]: string }>();
|
||||
expected.twoFactorProviders.set(1, { Email: "k***@bitwarden.com" });
|
||||
expected.twoFactorProviders = {
|
||||
[TwoFactorProviderType.Email]: { Email: "k***@bitwarden.com" },
|
||||
};
|
||||
expected.email = userEmail;
|
||||
expected.ssoEmail2FaSessionToken = ssoEmail2FaSessionToken;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
import { BehaviorSubject, filter, firstValueFrom, timeout } from "rxjs";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
@@ -101,7 +101,7 @@ export abstract class LoginStrategy {
|
||||
}
|
||||
|
||||
protected async startLogIn(): Promise<[AuthResult, IdentityResponse]> {
|
||||
this.twoFactorService.clearSelectedProvider();
|
||||
await this.twoFactorService.clearSelectedProvider();
|
||||
|
||||
const tokenRequest = this.cache.value.tokenRequest;
|
||||
const response = await this.apiService.postIdentityToken(tokenRequest);
|
||||
@@ -159,12 +159,12 @@ export abstract class LoginStrategy {
|
||||
* It also sets the access token and refresh token in the token service.
|
||||
*
|
||||
* @param {IdentityTokenResponse} tokenResponse - The response from the server containing the identity token.
|
||||
* @returns {Promise<void>} - A promise that resolves when the account information has been successfully saved.
|
||||
* @returns {Promise<UserId>} - A promise that resolves the the UserId when the account information has been successfully saved.
|
||||
*/
|
||||
protected async saveAccountInformation(tokenResponse: IdentityTokenResponse): Promise<UserId> {
|
||||
const accountInformation = await this.tokenService.decodeAccessToken(tokenResponse.accessToken);
|
||||
|
||||
const userId = accountInformation.sub;
|
||||
const userId = accountInformation.sub as UserId;
|
||||
|
||||
const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction({ userId });
|
||||
const vaultTimeout = await this.stateService.getVaultTimeout({ userId });
|
||||
@@ -191,6 +191,8 @@ export abstract class LoginStrategy {
|
||||
}),
|
||||
);
|
||||
|
||||
await this.verifyAccountAdded(userId);
|
||||
|
||||
await this.userDecryptionOptionsService.setUserDecryptionOptions(
|
||||
UserDecryptionOptions.fromResponse(tokenResponse),
|
||||
);
|
||||
@@ -207,7 +209,7 @@ export abstract class LoginStrategy {
|
||||
);
|
||||
|
||||
await this.billingAccountProfileStateService.setHasPremium(accountInformation.premium, false);
|
||||
return userId as UserId;
|
||||
return userId;
|
||||
}
|
||||
|
||||
protected async processTokenResponse(response: IdentityTokenResponse): Promise<AuthResult> {
|
||||
@@ -284,7 +286,7 @@ export abstract class LoginStrategy {
|
||||
const result = new AuthResult();
|
||||
result.twoFactorProviders = response.twoFactorProviders2;
|
||||
|
||||
this.twoFactorService.setProviders(response);
|
||||
await this.twoFactorService.setProviders(response);
|
||||
this.cache.next({ ...this.cache.value, captchaBypassToken: response.captchaToken ?? null });
|
||||
result.ssoEmail2FaSessionToken = response.ssoEmail2faSessionToken;
|
||||
result.email = response.email;
|
||||
@@ -306,4 +308,24 @@ export abstract class LoginStrategy {
|
||||
result.captchaSiteKey = response.siteKey;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the active account is set after initialization.
|
||||
* Note: In browser there is a slight delay between when active account emits in background,
|
||||
* and when it emits in foreground. We're giving the foreground 1 second to catch up.
|
||||
* If nothing is emitted, we throw an error.
|
||||
*/
|
||||
private async verifyAccountAdded(expectedUserId: UserId) {
|
||||
await firstValueFrom(
|
||||
this.accountService.activeAccount$.pipe(
|
||||
filter((account) => account?.id === expectedUserId),
|
||||
timeout({
|
||||
first: 1000,
|
||||
with: () => {
|
||||
throw new Error("Expected user never made active user after initialization.");
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,9 @@ describe("PasswordLoginStrategy", () => {
|
||||
kdfConfigService = mock<KdfConfigService>();
|
||||
|
||||
appIdService.getAppId.mockResolvedValue(deviceId);
|
||||
tokenService.decodeAccessToken.mockResolvedValue({});
|
||||
tokenService.decodeAccessToken.mockResolvedValue({
|
||||
sub: userId,
|
||||
});
|
||||
|
||||
loginStrategyService.makePreloginKey.mockResolvedValue(masterKey);
|
||||
|
||||
|
||||
@@ -92,7 +92,9 @@ describe("SsoLoginStrategy", () => {
|
||||
|
||||
tokenService.getTwoFactorToken.mockResolvedValue(null);
|
||||
appIdService.getAppId.mockResolvedValue(deviceId);
|
||||
tokenService.decodeAccessToken.mockResolvedValue({});
|
||||
tokenService.decodeAccessToken.mockResolvedValue({
|
||||
sub: userId,
|
||||
});
|
||||
|
||||
ssoLoginStrategy = new SsoLoginStrategy(
|
||||
null,
|
||||
|
||||
@@ -82,7 +82,9 @@ describe("UserApiLoginStrategy", () => {
|
||||
|
||||
appIdService.getAppId.mockResolvedValue(deviceId);
|
||||
tokenService.getTwoFactorToken.mockResolvedValue(null);
|
||||
tokenService.decodeAccessToken.mockResolvedValue({});
|
||||
tokenService.decodeAccessToken.mockResolvedValue({
|
||||
sub: userId,
|
||||
});
|
||||
|
||||
apiLogInStrategy = new UserApiLoginStrategy(
|
||||
cache,
|
||||
|
||||
@@ -18,7 +18,8 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { FakeAccountService } from "@bitwarden/common/spec";
|
||||
import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { PrfKey, UserKey } from "@bitwarden/common/types/key";
|
||||
|
||||
import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction";
|
||||
@@ -49,6 +50,7 @@ describe("WebAuthnLoginStrategy", () => {
|
||||
|
||||
const token = "mockToken";
|
||||
const deviceId = Utils.newGuid();
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
|
||||
let webAuthnCredentials!: WebAuthnLoginCredentials;
|
||||
|
||||
@@ -69,7 +71,7 @@ describe("WebAuthnLoginStrategy", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
accountService = new FakeAccountService(null);
|
||||
accountService = mockAccountServiceWith(userId);
|
||||
masterPasswordService = new FakeMasterPasswordService();
|
||||
|
||||
cryptoService = mock<CryptoService>();
|
||||
@@ -87,7 +89,9 @@ describe("WebAuthnLoginStrategy", () => {
|
||||
|
||||
tokenService.getTwoFactorToken.mockResolvedValue(null);
|
||||
appIdService.getAppId.mockResolvedValue(deviceId);
|
||||
tokenService.decodeAccessToken.mockResolvedValue({});
|
||||
tokenService.decodeAccessToken.mockResolvedValue({
|
||||
sub: userId,
|
||||
});
|
||||
|
||||
webAuthnLoginStrategy = new WebAuthnLoginStrategy(
|
||||
cache,
|
||||
|
||||
@@ -12,12 +12,12 @@ export interface TwoFactorProviderDetails {
|
||||
|
||||
export abstract class TwoFactorService {
|
||||
init: () => void;
|
||||
getSupportedProviders: (win: Window) => TwoFactorProviderDetails[];
|
||||
getDefaultProvider: (webAuthnSupported: boolean) => TwoFactorProviderType;
|
||||
setSelectedProvider: (type: TwoFactorProviderType) => void;
|
||||
clearSelectedProvider: () => void;
|
||||
getSupportedProviders: (win: Window) => Promise<TwoFactorProviderDetails[]>;
|
||||
getDefaultProvider: (webAuthnSupported: boolean) => Promise<TwoFactorProviderType>;
|
||||
setSelectedProvider: (type: TwoFactorProviderType) => Promise<void>;
|
||||
clearSelectedProvider: () => Promise<void>;
|
||||
|
||||
setProviders: (response: IdentityTwoFactorResponse) => void;
|
||||
clearProviders: () => void;
|
||||
getProviders: () => Map<TwoFactorProviderType, { [key: string]: string }>;
|
||||
setProviders: (response: IdentityTwoFactorResponse) => Promise<void>;
|
||||
clearProviders: () => Promise<void>;
|
||||
getProviders: () => Promise<Map<TwoFactorProviderType, { [key: string]: string }>>;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ export class AuthResult {
|
||||
resetMasterPassword = false;
|
||||
|
||||
forcePasswordReset: ForceSetPasswordReason = ForceSetPasswordReason.None;
|
||||
twoFactorProviders: Map<TwoFactorProviderType, { [key: string]: string }> = null;
|
||||
twoFactorProviders: Partial<Record<TwoFactorProviderType, Record<string, string>>> = null;
|
||||
ssoEmail2FaSessionToken?: string;
|
||||
email: string;
|
||||
requiresEncryptionKeyMigration: boolean;
|
||||
|
||||
@@ -4,8 +4,10 @@ import { TwoFactorProviderType } from "../../enums/two-factor-provider-type";
|
||||
import { MasterPasswordPolicyResponse } from "./master-password-policy.response";
|
||||
|
||||
export class IdentityTwoFactorResponse extends BaseResponse {
|
||||
// contains available two-factor providers
|
||||
twoFactorProviders: TwoFactorProviderType[];
|
||||
twoFactorProviders2 = new Map<TwoFactorProviderType, { [key: string]: string }>();
|
||||
// a map of two-factor providers to necessary data for completion
|
||||
twoFactorProviders2: Record<TwoFactorProviderType, Record<string, string>>;
|
||||
captchaToken: string;
|
||||
ssoEmail2faSessionToken: string;
|
||||
email?: string;
|
||||
@@ -15,15 +17,7 @@ export class IdentityTwoFactorResponse extends BaseResponse {
|
||||
super(response);
|
||||
this.captchaToken = this.getResponseProperty("CaptchaBypassToken");
|
||||
this.twoFactorProviders = this.getResponseProperty("TwoFactorProviders");
|
||||
const twoFactorProviders2 = this.getResponseProperty("TwoFactorProviders2");
|
||||
if (twoFactorProviders2 != null) {
|
||||
for (const prop in twoFactorProviders2) {
|
||||
// eslint-disable-next-line
|
||||
if (twoFactorProviders2.hasOwnProperty(prop)) {
|
||||
this.twoFactorProviders2.set(parseInt(prop, null), twoFactorProviders2[prop]);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.twoFactorProviders2 = this.getResponseProperty("TwoFactorProviders2");
|
||||
this.masterPasswordPolicy = new MasterPasswordPolicyResponse(
|
||||
this.getResponseProperty("MasterPasswordPolicy"),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { firstValueFrom, map } from "rxjs";
|
||||
|
||||
import { I18nService } from "../../platform/abstractions/i18n.service";
|
||||
import { PlatformUtilsService } from "../../platform/abstractions/platform-utils.service";
|
||||
import { Utils } from "../../platform/misc/utils";
|
||||
import { GlobalStateProvider, KeyDefinition, TWO_FACTOR_MEMORY } from "../../platform/state";
|
||||
import {
|
||||
TwoFactorProviderDetails,
|
||||
TwoFactorService as TwoFactorServiceAbstraction,
|
||||
@@ -59,13 +63,36 @@ export const TwoFactorProviders: Partial<Record<TwoFactorProviderType, TwoFactor
|
||||
},
|
||||
};
|
||||
|
||||
// Memory storage as only required during authentication process
|
||||
export const PROVIDERS = KeyDefinition.record<Record<string, string>, TwoFactorProviderType>(
|
||||
TWO_FACTOR_MEMORY,
|
||||
"providers",
|
||||
{
|
||||
deserializer: (obj) => obj,
|
||||
},
|
||||
);
|
||||
|
||||
// Memory storage as only required during authentication process
|
||||
export const SELECTED_PROVIDER = new KeyDefinition<TwoFactorProviderType>(
|
||||
TWO_FACTOR_MEMORY,
|
||||
"selected",
|
||||
{
|
||||
deserializer: (obj) => obj,
|
||||
},
|
||||
);
|
||||
|
||||
export class TwoFactorService implements TwoFactorServiceAbstraction {
|
||||
private twoFactorProvidersData: Map<TwoFactorProviderType, { [key: string]: string }>;
|
||||
private selectedTwoFactorProviderType: TwoFactorProviderType = null;
|
||||
private providersState = this.globalStateProvider.get(PROVIDERS);
|
||||
private selectedState = this.globalStateProvider.get(SELECTED_PROVIDER);
|
||||
readonly providers$ = this.providersState.state$.pipe(
|
||||
map((providers) => Utils.recordToMap(providers)),
|
||||
);
|
||||
readonly selected$ = this.selectedState.state$;
|
||||
|
||||
constructor(
|
||||
private i18nService: I18nService,
|
||||
private platformUtilsService: PlatformUtilsService,
|
||||
private globalStateProvider: GlobalStateProvider,
|
||||
) {}
|
||||
|
||||
init() {
|
||||
@@ -93,63 +120,60 @@ export class TwoFactorService implements TwoFactorServiceAbstraction {
|
||||
this.i18nService.t("yubiKeyDesc");
|
||||
}
|
||||
|
||||
getSupportedProviders(win: Window): TwoFactorProviderDetails[] {
|
||||
async getSupportedProviders(win: Window): Promise<TwoFactorProviderDetails[]> {
|
||||
const data = await firstValueFrom(this.providers$);
|
||||
const providers: any[] = [];
|
||||
if (this.twoFactorProvidersData == null) {
|
||||
if (data == null) {
|
||||
return providers;
|
||||
}
|
||||
|
||||
if (
|
||||
this.twoFactorProvidersData.has(TwoFactorProviderType.OrganizationDuo) &&
|
||||
data.has(TwoFactorProviderType.OrganizationDuo) &&
|
||||
this.platformUtilsService.supportsDuo()
|
||||
) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.OrganizationDuo]);
|
||||
}
|
||||
|
||||
if (this.twoFactorProvidersData.has(TwoFactorProviderType.Authenticator)) {
|
||||
if (data.has(TwoFactorProviderType.Authenticator)) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.Authenticator]);
|
||||
}
|
||||
|
||||
if (this.twoFactorProvidersData.has(TwoFactorProviderType.Yubikey)) {
|
||||
if (data.has(TwoFactorProviderType.Yubikey)) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.Yubikey]);
|
||||
}
|
||||
|
||||
if (
|
||||
this.twoFactorProvidersData.has(TwoFactorProviderType.Duo) &&
|
||||
this.platformUtilsService.supportsDuo()
|
||||
) {
|
||||
if (data.has(TwoFactorProviderType.Duo) && this.platformUtilsService.supportsDuo()) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.Duo]);
|
||||
}
|
||||
|
||||
if (
|
||||
this.twoFactorProvidersData.has(TwoFactorProviderType.WebAuthn) &&
|
||||
data.has(TwoFactorProviderType.WebAuthn) &&
|
||||
this.platformUtilsService.supportsWebAuthn(win)
|
||||
) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.WebAuthn]);
|
||||
}
|
||||
|
||||
if (this.twoFactorProvidersData.has(TwoFactorProviderType.Email)) {
|
||||
if (data.has(TwoFactorProviderType.Email)) {
|
||||
providers.push(TwoFactorProviders[TwoFactorProviderType.Email]);
|
||||
}
|
||||
|
||||
return providers;
|
||||
}
|
||||
|
||||
getDefaultProvider(webAuthnSupported: boolean): TwoFactorProviderType {
|
||||
if (this.twoFactorProvidersData == null) {
|
||||
async getDefaultProvider(webAuthnSupported: boolean): Promise<TwoFactorProviderType> {
|
||||
const data = await firstValueFrom(this.providers$);
|
||||
const selected = await firstValueFrom(this.selected$);
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
this.selectedTwoFactorProviderType != null &&
|
||||
this.twoFactorProvidersData.has(this.selectedTwoFactorProviderType)
|
||||
) {
|
||||
return this.selectedTwoFactorProviderType;
|
||||
if (selected != null && data.has(selected)) {
|
||||
return selected;
|
||||
}
|
||||
|
||||
let providerType: TwoFactorProviderType = null;
|
||||
let providerPriority = -1;
|
||||
this.twoFactorProvidersData.forEach((_value, type) => {
|
||||
data.forEach((_value, type) => {
|
||||
const provider = (TwoFactorProviders as any)[type];
|
||||
if (provider != null && provider.priority > providerPriority) {
|
||||
if (type === TwoFactorProviderType.WebAuthn && !webAuthnSupported) {
|
||||
@@ -164,23 +188,23 @@ export class TwoFactorService implements TwoFactorServiceAbstraction {
|
||||
return providerType;
|
||||
}
|
||||
|
||||
setSelectedProvider(type: TwoFactorProviderType) {
|
||||
this.selectedTwoFactorProviderType = type;
|
||||
async setSelectedProvider(type: TwoFactorProviderType): Promise<void> {
|
||||
await this.selectedState.update(() => type);
|
||||
}
|
||||
|
||||
clearSelectedProvider() {
|
||||
this.selectedTwoFactorProviderType = null;
|
||||
async clearSelectedProvider(): Promise<void> {
|
||||
await this.selectedState.update(() => null);
|
||||
}
|
||||
|
||||
setProviders(response: IdentityTwoFactorResponse) {
|
||||
this.twoFactorProvidersData = response.twoFactorProviders2;
|
||||
async setProviders(response: IdentityTwoFactorResponse): Promise<void> {
|
||||
await this.providersState.update(() => response.twoFactorProviders2);
|
||||
}
|
||||
|
||||
clearProviders() {
|
||||
this.twoFactorProvidersData = null;
|
||||
async clearProviders(): Promise<void> {
|
||||
await this.providersState.update(() => null);
|
||||
}
|
||||
|
||||
getProviders() {
|
||||
return this.twoFactorProvidersData;
|
||||
getProviders(): Promise<Map<TwoFactorProviderType, { [key: string]: string }>> {
|
||||
return firstValueFrom(this.providers$);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { record } from "./deserialization-helpers";
|
||||
|
||||
describe("deserialization helpers", () => {
|
||||
describe("record", () => {
|
||||
it("deserializes a record when keys are strings", () => {
|
||||
const deserializer = record((value: number) => value);
|
||||
const input = {
|
||||
a: 1,
|
||||
b: 2,
|
||||
};
|
||||
const output = deserializer(input);
|
||||
expect(output).toEqual(input);
|
||||
});
|
||||
|
||||
it("deserializes a record when keys are numbers", () => {
|
||||
const deserializer = record((value: number) => value);
|
||||
const input = {
|
||||
1: 1,
|
||||
2: 2,
|
||||
};
|
||||
const output = deserializer(input);
|
||||
expect(output).toEqual(input);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ export function array<T>(
|
||||
*
|
||||
* @param valueDeserializer
|
||||
*/
|
||||
export function record<T, TKey extends string = string>(
|
||||
export function record<T, TKey extends string | number = string>(
|
||||
valueDeserializer: (value: Jsonify<T>) => T,
|
||||
): (record: Jsonify<Record<TKey, T>>) => Record<TKey, T> {
|
||||
return (jsonValue: Jsonify<Record<TKey, T> | null>) => {
|
||||
@@ -29,10 +29,10 @@ export function record<T, TKey extends string = string>(
|
||||
return null;
|
||||
}
|
||||
|
||||
const output: Record<string, T> = {};
|
||||
for (const key in jsonValue) {
|
||||
output[key] = valueDeserializer((jsonValue as Record<string, Jsonify<T>>)[key]);
|
||||
}
|
||||
const output: Record<TKey, T> = {} as any;
|
||||
Object.entries(jsonValue).forEach(([key, value]) => {
|
||||
output[key as TKey] = valueDeserializer(value);
|
||||
});
|
||||
return output;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ export class KeyDefinition<T> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
static record<T, TKey extends string = string>(
|
||||
static record<T, TKey extends string | number = string>(
|
||||
stateDefinition: StateDefinition,
|
||||
key: string,
|
||||
// We have them provide options for the value of the record, depending on future options we add, this could get a little weird.
|
||||
|
||||
@@ -40,6 +40,7 @@ export const KEY_CONNECTOR_DISK = new StateDefinition("keyConnector", "disk");
|
||||
export const ACCOUNT_MEMORY = new StateDefinition("account", "memory");
|
||||
export const MASTER_PASSWORD_MEMORY = new StateDefinition("masterPassword", "memory");
|
||||
export const MASTER_PASSWORD_DISK = new StateDefinition("masterPassword", "disk");
|
||||
export const TWO_FACTOR_MEMORY = new StateDefinition("twoFactor", "memory");
|
||||
export const AVATAR_DISK = new StateDefinition("avatar", "disk", { web: "disk-local" });
|
||||
export const ROUTER_DISK = new StateDefinition("router", "disk");
|
||||
export const LOGIN_EMAIL_DISK = new StateDefinition("loginEmail", "disk", {
|
||||
|
||||
@@ -120,7 +120,7 @@ export class UserKeyDefinition<T> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
static record<T, TKey extends string = string>(
|
||||
static record<T, TKey extends string | number = string>(
|
||||
stateDefinition: StateDefinition,
|
||||
key: string,
|
||||
// We have them provide options for the value of the record, depending on future options we add, this could get a little weird.
|
||||
|
||||
Reference in New Issue
Block a user