1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-15 07:43:35 +00:00
Files
browser/apps/desktop/src/app/accounts/settings.component.ts
Jared Snider 473c5311fa Auth/PM-5501 - VaultTimeoutSettingsService State Provider Migration (#8604)
* PM-5501 - VaultTimeoutSettingsSvc - refactor var names in getVaultTimeoutAction

* PM-5501 - Add state definitions and key definitions + test deserialization of key defs.

* PM-5501 - Add state provider dep to VaultTimeoutSettingsSvc

* PM-5501 - Refactor getVaultTimeout

* PM-5501 - VaultTimeoutSettingsService - Build getMaxVaultTimeoutPolicyByUserId helper

* PM-5501 - (1) Update state definitions (2) convert KeyDefs to UserKeyDefs (2) Remove everBeenUnlocked as we won't need it

* PM-5501 - VaultTimeoutSettingsSvc - POC for getVaultTimeoutActionByUserId$ method + new private determineVaultTimeoutAction helper.

* PM-5501 - VaultTimeoutSettingsSvc - build set and observable get methods for vault timeout settings

* PM-5501 - Update web references to use new vault timeout setting service methods

* PM-5501 - VaultTimeoutSettingsSvc - write up abstraction js docs

* PM-5501 - VaultTimeoutSettingsSvc abstraction - finish tweaks

* PM-5501 - VaultTimeoutSettingsSvc - add catchError blocks to observables to protect outer observables and prevent cancellation in case of error.

* PM-5501 - Remove vault timeout settings from state service implementation.

* PM-5501 - VaultTimeoutSettingsServiceStateProviderMigrator first draft

* PM-5501 - WIP - replace some state service calls with calls to vault timeout settings svc.

* PM-5501 - Replace state service calls in login strategies to get vault timeout settings data with VaultTimeoutSettingsService calls.

* PM-5501 - Fix login strategy tests

* PM-5501 - Update login strategy tests to pass

* PM-5501 - CryptoSvc - share VaultTimeout user key def to allow crypto svc access to the vault timeout without creating a circular dep.

* PM-5501 - Fix dependency injections.

* PM-5501 - ApiSvc - replace state svc with vault timeout settings svc.

* PM-5501 - VaultTimeoutSettingsServiceStateProviderMigrator more cleanup

* PM-5501 - Test VaultTimeoutSettingsServiceStateProviderMigrator

* PM-5501 - VaultTimeoutSettingsSvc tests updated

* PM-5501 - Update all setVaultTimeoutOptions references

* PM-5501 - VaultTimeoutSettingsSvc - Update setVaultTimeoutOptions to remove unnecessary logic and clean up clearTokens condition.

* PM-5501 - Fix vault timeout service tests

* PM-5501 - Update VaultTimeoutSettings state tests to pass

* PM-5501 - Desktop - system svc - fix build by replacing use of removed method.

* PM-5501 - Fix CLI by properly configuring super class deps in NodeApiService

* PM-5501 - Actually finish getitng deps fixed to get CLI to build

* PM-5501 - VaultTimeoutSettingsSvc.determineVaultTimeoutAction - pass userId to getAvailableVaultTimeoutActions to prevent hang waiting for an active user.

* PM-5501 - VaultTimeoutSettingSvc test - enhance getVaultTimeoutActionByUserId$ to also test PIN scenarios as an unlock method

* PM-5501 - bump migration version

* PM-5501 - Refactor migration to ensure the migration persists null vault timeout values.

* PM-5501 - Bump migration version

* PM-5501 - Fix web build issues introduced by merging main.

* PM-5501 - Bump migration version

* PM-5501 - PreferencesComponent - revert dep change from InternalPolicyService to standard PolicyService abstraction

* PM-5501 - Address all PR feedback from Jake

Co-authored-by: Jake Fink <jfink@bitwarden.com>

* PM-5501 - VaultTimeoutSettingsSvc tests - add tests for setVaultTimeoutOptions

* PM-5501 - VaultTimeoutSettingsSvc - setVaultTimeoutOptions - Update tests to use platform's desired syntax.

* PM-5501 - Fix tests

* PM-5501 - Create new VaultTimeout type

* PM-5501 - Create new DEFAULT_VAULT_TIMEOUT to allow each client to inject their default timeout into the VaultTimeoutSettingService

* PM-5501 - Migrate client default vault timeout to new injection token

* PM-5501 - Update VaultTimeoutSettingsSvc to use VaultTimeout type and apply default vault timeout if it is null.

* PM-5501 - Update vaultTimeout: number to be vaultTimeout: VaultTimeout everywhere I could find it.

* PM-5501 - More changes based on changing vaultTimeout from number to VaultTimeout type.

* PM-5501 - VaultTimeoutSvc - Update shouldLock logic which previously checked for null (never) or any negative values (any strings except never) with a simple string type check.

* PM-5501 - More cleanup of vaultTimeout type change - replacing null checks with "never" checks

* PM-5501 - VaultTimeoutSettingsSvc - refactor determineVaultTimeout to properly treat string and numeric vault timeouts.

* PM-5501 - Update vault timeout settings service tests to reflect new VaultTimeout type.

* PM-5501 - VaultTimeoutSettingsService - add more test cases for getVaultTimeoutByUserId

* PM-5501 - (1) Remove "immediately" as 0 is numerically meaningful and can be used with Math.min (2) Add VaultTimeoutOption interface for use in all places we show the user a list of vault timeout options.

* PM-5501 - VaultTimeoutSettingSvc - update tests to use 0 as immediately.

* PM-5501 - VaultTimeoutInputComp - Add new types and update applyVaultTimeoutPolicy logic appropriately.

* PM-5501 - Add new types to all preferences and setting components across clients.

* PM-5501 - Fix bug on web where navigating to the preferences page throws an error b/c the validatorChange function isn't defined.

* PM-5501 - WIP on updating vault timeout setting migration and rollback + testing it.

* PM-5501 - Update VaultTimeoutSettingsSvc state provider migration and tests to map existing possible values into new VaultTImeout type.

* PM-5501 - Fix vault timeout settings state tests by changing number to new VaultTimeout type.

* PM-5501 - Fix crypto svc auto key refresh test to use "never" instead of null.

* PM-5501 - Add clarifying comment to vaulttimeout type

* PM-5501 - Desktop app comp - replace systemTimeoutOptions with vault timeout type.

* PM-5501 - Update vault timeout service tests to use VaultTimeout type.

* PM-5501 - VaultTimeoutSettingsSvc - (1) Fix bug where vault timeout action didn't have a default like it did before (2) Fix bug in userHasMasterPassword where it would incorrectly return the active user stream for a given user id as a fallback. There is no guarantee the given user would match the active user so the paths are mutually exclusive.

* PM-5501 - Login Strategy fix - Move retrieval of vault timeout settings and setting of the tokens until after account init and user decryption options set as those opts are needed to properly determine the user's available vault timeout actions.

* PM-5501 - Fix vault timeout settings svc tests

* PM-5501 - VaultTimeoutSettingSvc - move default logic to determine methods + refactor default vault timeout action to properly default to lock in scenarios the user has lock available.

* Update libs/angular/src/components/settings/vault-timeout-input.component.ts

Co-authored-by: Cesar Gonzalez <cesar.a.gonzalezcs@gmail.com>

* PM-5501 - Per PR feedback, cleanup commented out vault timeout options

* PM-5501 - Fix vault timeout input comp lint issues

* PM-5501 - Per PR feedback from Cesar, update VaultTimeout type to use const so we can avoid any magic string usage. Awesome.

Co-authored-by: Cesar Gonzalez <cesar.a.gonzalezcs@gmail.com>

* PM-5501 - CLI - use "never" as default vault timeout instead of null.

* PM-5501 - Fix broken tests

* PM-5501 - Bump migration version

* PM-5501 - Fix build errors after merging main.

* PM-5501 - Update mockMigrationHelper to pass along client type so tests will respect it.

* PM-5501 - Update VaultTimeoutSettingsServiceStateProviderMigrator and tests to use new CLI client type to convert undefined values to never so that CLI users don't lose their session upon running this migration.

* PM-5501 - Bump migration version

* PM-5501 - Fix migration tests to use new authenticated user format

* PM-5501 Update rollback tests

* PM-5501 - Adjust migration based on feedback.

* PM-5501 - Per Jake's find, fix missed -2

Co-authored-by: Jake Fink <jfink@bitwarden.com>

* PM-5501 - Add user id to needsStorageReseed.

Co-authored-by: Jake Fink <jfink@bitwarden.com>

* PM-5501 - Per PR feedback, setVaultTimeoutOptions shouldn't accept null for vault timeout anymore.

* PM-5501 - Per PR feedback, add null checks for set methods for setting vault timeout or vault timeout action.

* PM-5501 - Per PR feedback, add more context as to why we need vault timeout settings to persist after logout.

* PM-5501 - Per PR feedback, fix userHasMasterPassword

* PM-5501 - VaultTimeoutSettingsService - fix userHasMasterPassword check by checking for null decryption options.

* PM-5501 - Remove state service from vault timeout settings service (WOOO)

* PM-5501 - Bump migration version

* PM-5501 - Account Security comp - refactor to consider ease of debugging.

* PM-5501 - (1) Add checks for null vault timeout and vault timeout actions (2) Add tests for new scenarios.

* PM-5501 - VaultTimeoutSettingsSvc - setVaultTimeoutOptions - fix bug where nullish check would throw incorrectly if immediately (0) was picked as the timeout.

* PM-5501 - Per PR feedback, clean up remaining token service methods which accept null for timeout and add tests. .

* PM-5501 - Fix nit

---------

Co-authored-by: Jake Fink <jfink@bitwarden.com>
Co-authored-by: Cesar Gonzalez <cesar.a.gonzalezcs@gmail.com>
2024-05-13 15:56:04 -04:00

767 lines
29 KiB
TypeScript

import { Component, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { BehaviorSubject, Observable, Subject, firstValueFrom } from "rxjs";
import { concatMap, debounceTime, filter, map, switchMap, takeUntil, tap } from "rxjs/operators";
import { AuthRequestServiceAbstraction, PinServiceAbstraction } from "@bitwarden/auth/common";
import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { UserVerificationService as UserVerificationServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service";
import { DeviceType } from "@bitwarden/common/enums";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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 { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { BiometricStateService } from "@bitwarden/common/platform/biometrics/biometric-state.service";
import { KeySuffixOptions, ThemeType } from "@bitwarden/common/platform/enums";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { ThemeStateService } from "@bitwarden/common/platform/theming/theme-state.service";
import { UserId } from "@bitwarden/common/types/guid";
import {
VaultTimeout,
VaultTimeoutOption,
VaultTimeoutStringType,
} from "@bitwarden/common/types/vault-timeout.type";
import { DialogService } from "@bitwarden/components";
import { SetPinComponent } from "../../auth/components/set-pin.component";
import { DesktopAutofillSettingsService } from "../../autofill/services/desktop-autofill-settings.service";
import { DesktopSettingsService } from "../../platform/services/desktop-settings.service";
import { NativeMessagingManifestService } from "../services/native-messaging-manifest.service";
@Component({
selector: "app-settings",
templateUrl: "settings.component.html",
})
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
export class SettingsComponent implements OnInit {
// For use in template
protected readonly VaultTimeoutAction = VaultTimeoutAction;
showMinToTray = false;
vaultTimeoutOptions: VaultTimeoutOption[];
localeOptions: any[];
themeOptions: any[];
clearClipboardOptions: any[];
supportsBiometric: boolean;
showAlwaysShowDock = false;
requireEnableTray = false;
showDuckDuckGoIntegrationOption = false;
isWindows: boolean;
enableTrayText: string;
enableTrayDescText: string;
enableMinToTrayText: string;
enableMinToTrayDescText: string;
enableCloseToTrayText: string;
enableCloseToTrayDescText: string;
startToTrayText: string;
startToTrayDescText: string;
showSecurity = true;
showAccountPreferences = true;
showAppPreferences = true;
currentUserEmail: string;
currentUserId: UserId;
availableVaultTimeoutActions$: Observable<VaultTimeoutAction[]>;
vaultTimeoutPolicyCallout: Observable<{
timeout: { hours: number; minutes: number };
action: "lock" | "logOut";
}>;
previousVaultTimeout: VaultTimeout = null;
userHasMasterPassword: boolean;
userHasPinSet: boolean;
form = this.formBuilder.group({
// Security
vaultTimeout: [null as VaultTimeout | null],
vaultTimeoutAction: [VaultTimeoutAction.Lock],
pin: [null as boolean | null],
biometric: false,
autoPromptBiometrics: false,
requirePasswordOnStart: false,
approveLoginRequests: false,
// Account Preferences
clearClipboard: [null],
minimizeOnCopyToClipboard: false,
enableFavicons: false,
// App Settings
enableTray: false,
enableMinToTray: false,
enableCloseToTray: false,
startToTray: false,
openAtLogin: false,
alwaysShowDock: false,
enableBrowserIntegration: false,
enableBrowserIntegrationFingerprint: this.formBuilder.control<boolean>({
value: false,
disabled: true,
}),
enableHardwareAcceleration: true,
enableDuckDuckGoBrowserIntegration: false,
theme: [null as ThemeType | null],
locale: [null as string | null],
});
private refreshTimeoutSettings$ = new BehaviorSubject<void>(undefined);
private destroy$ = new Subject<void>();
constructor(
private accountService: AccountService,
private policyService: PolicyService,
private formBuilder: FormBuilder,
private i18nService: I18nService,
private platformUtilsService: PlatformUtilsService,
private vaultTimeoutSettingsService: VaultTimeoutSettingsService,
private stateService: StateService,
private autofillSettingsService: AutofillSettingsServiceAbstraction,
private messagingService: MessagingService,
private cryptoService: CryptoService,
private themeStateService: ThemeStateService,
private domainSettingsService: DomainSettingsService,
private dialogService: DialogService,
private userVerificationService: UserVerificationServiceAbstraction,
private desktopSettingsService: DesktopSettingsService,
private biometricStateService: BiometricStateService,
private desktopAutofillSettingsService: DesktopAutofillSettingsService,
private pinService: PinServiceAbstraction,
private authRequestService: AuthRequestServiceAbstraction,
private logService: LogService,
private nativeMessagingManifestService: NativeMessagingManifestService,
) {
const isMac = this.platformUtilsService.getDevice() === DeviceType.MacOsDesktop;
// Workaround to avoid ghosting trays https://github.com/electron/electron/issues/17622
this.requireEnableTray = this.platformUtilsService.getDevice() === DeviceType.LinuxDesktop;
const trayKey = isMac ? "enableMenuBar" : "enableTray";
this.enableTrayText = this.i18nService.t(trayKey);
this.enableTrayDescText = this.i18nService.t(trayKey + "Desc");
const minToTrayKey = isMac ? "enableMinToMenuBar" : "enableMinToTray";
this.enableMinToTrayText = this.i18nService.t(minToTrayKey);
this.enableMinToTrayDescText = this.i18nService.t(minToTrayKey + "Desc");
const closeToTrayKey = isMac ? "enableCloseToMenuBar" : "enableCloseToTray";
this.enableCloseToTrayText = this.i18nService.t(closeToTrayKey);
this.enableCloseToTrayDescText = this.i18nService.t(closeToTrayKey + "Desc");
const startToTrayKey = isMac ? "startToMenuBar" : "startToTray";
this.startToTrayText = this.i18nService.t(startToTrayKey);
this.startToTrayDescText = this.i18nService.t(startToTrayKey + "Desc");
// DuckDuckGo browser is only for macos initially
this.showDuckDuckGoIntegrationOption = isMac;
this.vaultTimeoutOptions = [
{ name: this.i18nService.t("oneMinute"), value: 1 },
{ name: this.i18nService.t("fiveMinutes"), value: 5 },
{ name: this.i18nService.t("fifteenMinutes"), value: 15 },
{ name: this.i18nService.t("thirtyMinutes"), value: 30 },
{ name: this.i18nService.t("oneHour"), value: 60 },
{ name: this.i18nService.t("fourHours"), value: 240 },
{ name: this.i18nService.t("onIdle"), value: VaultTimeoutStringType.OnIdle },
{ name: this.i18nService.t("onSleep"), value: VaultTimeoutStringType.OnSleep },
];
if (this.platformUtilsService.getDevice() !== DeviceType.LinuxDesktop) {
this.vaultTimeoutOptions.push({
name: this.i18nService.t("onLocked"),
value: VaultTimeoutStringType.OnLocked,
});
}
this.vaultTimeoutOptions = this.vaultTimeoutOptions.concat([
{ name: this.i18nService.t("onRestart"), value: VaultTimeoutStringType.OnRestart },
{ name: this.i18nService.t("never"), value: VaultTimeoutStringType.Never },
]);
const localeOptions: any[] = [];
this.i18nService.supportedTranslationLocales.forEach((locale) => {
let name = locale;
if (this.i18nService.localeNames.has(locale)) {
name += " - " + this.i18nService.localeNames.get(locale);
}
localeOptions.push({ name: name, value: locale });
});
localeOptions.sort(Utils.getSortFunction(this.i18nService, "name"));
localeOptions.splice(0, 0, { name: this.i18nService.t("default"), value: null });
this.localeOptions = localeOptions;
this.themeOptions = [
{ name: this.i18nService.t("default"), value: ThemeType.System },
{ name: this.i18nService.t("light"), value: ThemeType.Light },
{ name: this.i18nService.t("dark"), value: ThemeType.Dark },
{ name: "Nord", value: ThemeType.Nord },
];
this.clearClipboardOptions = [
{ name: this.i18nService.t("never"), value: null },
{ name: this.i18nService.t("tenSeconds"), value: 10 },
{ name: this.i18nService.t("twentySeconds"), value: 20 },
{ name: this.i18nService.t("thirtySeconds"), value: 30 },
{ name: this.i18nService.t("oneMinute"), value: 60 },
{ name: this.i18nService.t("twoMinutes"), value: 120 },
{ name: this.i18nService.t("fiveMinutes"), value: 300 },
];
}
async ngOnInit() {
this.userHasMasterPassword = await this.userVerificationService.hasMasterPassword();
this.isWindows = (await this.platformUtilsService.getDevice()) === DeviceType.WindowsDesktop;
if ((await this.stateService.getUserId()) == null) {
return;
}
this.currentUserEmail = await this.stateService.getEmail();
this.currentUserId = (await this.stateService.getUserId()) as UserId;
this.availableVaultTimeoutActions$ = this.refreshTimeoutSettings$.pipe(
switchMap(() => this.vaultTimeoutSettingsService.availableVaultTimeoutActions$()),
);
// Load timeout policy
this.vaultTimeoutPolicyCallout = this.policyService.get$(PolicyType.MaximumVaultTimeout).pipe(
filter((policy) => policy != null),
map((policy) => {
let timeout;
if (policy.data?.minutes) {
timeout = {
hours: Math.floor(policy.data?.minutes / 60),
minutes: policy.data?.minutes % 60,
};
}
return { timeout: timeout, action: policy.data?.action };
}),
tap((policy) => {
if (policy.action) {
this.form.controls.vaultTimeoutAction.disable({ emitEvent: false });
} else {
this.form.controls.vaultTimeoutAction.enable({ emitEvent: false });
}
}),
);
const userId = (await firstValueFrom(this.accountService.activeAccount$))?.id;
// Load initial values
this.userHasPinSet = await this.pinService.isPinSet(userId);
const activeAccount = await firstValueFrom(this.accountService.activeAccount$);
const initialValues = {
vaultTimeout: await firstValueFrom(
this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(activeAccount.id),
),
vaultTimeoutAction: await firstValueFrom(
this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(activeAccount.id),
),
pin: this.userHasPinSet,
biometric: await this.vaultTimeoutSettingsService.isBiometricLockSet(),
autoPromptBiometrics: await firstValueFrom(this.biometricStateService.promptAutomatically$),
requirePasswordOnStart: await firstValueFrom(
this.biometricStateService.requirePasswordOnStart$,
),
approveLoginRequests:
(await this.authRequestService.getAcceptAuthRequests(this.currentUserId)) ?? false,
clearClipboard: await firstValueFrom(this.autofillSettingsService.clearClipboardDelay$),
minimizeOnCopyToClipboard: await this.stateService.getMinimizeOnCopyToClipboard(),
enableFavicons: await firstValueFrom(this.domainSettingsService.showFavicons$),
enableTray: await firstValueFrom(this.desktopSettingsService.trayEnabled$),
enableMinToTray: await firstValueFrom(this.desktopSettingsService.minimizeToTray$),
enableCloseToTray: await firstValueFrom(this.desktopSettingsService.closeToTray$),
startToTray: await firstValueFrom(this.desktopSettingsService.startToTray$),
openAtLogin: await firstValueFrom(this.desktopSettingsService.openAtLogin$),
alwaysShowDock: await firstValueFrom(this.desktopSettingsService.alwaysShowDock$),
enableBrowserIntegration: await this.stateService.getEnableBrowserIntegration(),
enableBrowserIntegrationFingerprint:
await this.stateService.getEnableBrowserIntegrationFingerprint(),
enableDuckDuckGoBrowserIntegration: await firstValueFrom(
this.desktopAutofillSettingsService.enableDuckDuckGoBrowserIntegration$,
),
enableHardwareAcceleration: await firstValueFrom(
this.desktopSettingsService.hardwareAcceleration$,
),
theme: await firstValueFrom(this.themeStateService.selectedTheme$),
locale: await firstValueFrom(this.i18nService.userSetLocale$),
};
this.form.setValue(initialValues, { emitEvent: false });
if (this.form.value.enableBrowserIntegration) {
this.form.controls.enableBrowserIntegrationFingerprint.enable();
}
// Non-form values
this.showMinToTray = this.platformUtilsService.getDevice() !== DeviceType.LinuxDesktop;
this.showAlwaysShowDock = this.platformUtilsService.getDevice() === DeviceType.MacOsDesktop;
this.supportsBiometric = await this.platformUtilsService.supportsBiometric();
this.previousVaultTimeout = this.form.value.vaultTimeout;
this.refreshTimeoutSettings$
.pipe(
switchMap(() =>
this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(activeAccount.id),
),
takeUntil(this.destroy$),
)
.subscribe((action) => {
this.form.controls.vaultTimeoutAction.setValue(action, { emitEvent: false });
});
// Form events
this.form.controls.vaultTimeout.valueChanges
.pipe(
debounceTime(500),
concatMap(async (value) => {
await this.saveVaultTimeout(value);
}),
takeUntil(this.destroy$),
)
.subscribe();
this.form.controls.vaultTimeoutAction.valueChanges
.pipe(
concatMap(async (action) => {
await this.saveVaultTimeoutAction(action);
}),
takeUntil(this.destroy$),
)
.subscribe();
this.form.controls.pin.valueChanges
.pipe(
concatMap(async (value) => {
await this.updatePin(value);
this.refreshTimeoutSettings$.next();
}),
takeUntil(this.destroy$),
)
.subscribe();
this.form.controls.biometric.valueChanges
.pipe(
concatMap(async (enabled) => {
await this.updateBiometric(enabled);
this.refreshTimeoutSettings$.next();
}),
takeUntil(this.destroy$),
)
.subscribe();
this.form.controls.enableBrowserIntegration.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe((enabled) => {
if (enabled) {
this.form.controls.enableBrowserIntegrationFingerprint.enable();
} else {
this.form.controls.enableBrowserIntegrationFingerprint.disable();
}
});
}
async saveVaultTimeout(newValue: VaultTimeout) {
if (newValue == null) {
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "warning" },
content: { key: "neverLockWarning" },
type: "warning",
});
if (!confirmed) {
this.form.controls.vaultTimeout.setValue(this.previousVaultTimeout);
return;
}
}
// Avoid saving 0 since it's useless as a timeout value.
if (this.form.value.vaultTimeout === 0) {
return;
}
if (!this.form.controls.vaultTimeout.valid) {
this.platformUtilsService.showToast(
"error",
null,
this.i18nService.t("vaultTimeoutTooLarge"),
);
return;
}
this.previousVaultTimeout = this.form.value.vaultTimeout;
const activeAccount = await firstValueFrom(this.accountService.activeAccount$);
await this.vaultTimeoutSettingsService.setVaultTimeoutOptions(
activeAccount.id,
newValue,
this.form.value.vaultTimeoutAction,
);
}
async saveVaultTimeoutAction(newValue: VaultTimeoutAction) {
if (newValue === "logOut") {
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "vaultTimeoutLogOutConfirmationTitle" },
content: { key: "vaultTimeoutLogOutConfirmation" },
type: "warning",
});
if (!confirmed) {
this.form.controls.vaultTimeoutAction.patchValue(VaultTimeoutAction.Lock, {
emitEvent: false,
});
return;
}
}
if (this.form.controls.vaultTimeout.hasError("policyError")) {
this.platformUtilsService.showToast(
"error",
null,
this.i18nService.t("vaultTimeoutTooLarge"),
);
return;
}
const activeAccount = await firstValueFrom(this.accountService.activeAccount$);
await this.vaultTimeoutSettingsService.setVaultTimeoutOptions(
activeAccount.id,
this.form.value.vaultTimeout,
newValue,
);
}
async updatePin(value: boolean) {
if (value) {
const dialogRef = SetPinComponent.open(this.dialogService);
if (dialogRef == null) {
this.form.controls.pin.setValue(false, { emitEvent: false });
return;
}
this.userHasPinSet = await firstValueFrom(dialogRef.closed);
this.form.controls.pin.setValue(this.userHasPinSet, { emitEvent: false });
}
if (!value) {
// If user turned off PIN without having a MP and has biometric + require MP/PIN on restart enabled
if (this.form.value.requirePasswordOnStart && !this.userHasMasterPassword) {
// then must turn that off to prevent user from getting into bad state
this.form.controls.requirePasswordOnStart.setValue(false);
await this.updateRequirePasswordOnStart();
}
await this.vaultTimeoutSettingsService.clear();
}
this.messagingService.send("redrawMenu");
}
async updateBiometric(enabled: boolean) {
// NOTE: A bug in angular causes [ngModel] to not reflect the backing field value
// causing the checkbox to remain checked even if authentication fails.
// The bug should resolve itself once the angular issue is resolved.
// See: https://github.com/angular/angular/issues/13063
try {
if (!enabled || !this.supportsBiometric) {
this.form.controls.biometric.setValue(false, { emitEvent: false });
await this.biometricStateService.setBiometricUnlockEnabled(false);
await this.cryptoService.refreshAdditionalKeys();
return;
}
await this.biometricStateService.setBiometricUnlockEnabled(true);
if (this.isWindows) {
// Recommended settings for Windows Hello
this.form.controls.requirePasswordOnStart.setValue(true);
this.form.controls.autoPromptBiometrics.setValue(false);
await this.biometricStateService.setPromptAutomatically(false);
await this.biometricStateService.setRequirePasswordOnStart(true);
await this.biometricStateService.setDismissedRequirePasswordOnStartCallout();
}
await this.cryptoService.refreshAdditionalKeys();
// Validate the key is stored in case biometrics fail.
const biometricSet = await this.cryptoService.hasUserKeyStored(KeySuffixOptions.Biometric);
this.form.controls.biometric.setValue(biometricSet, { emitEvent: false });
if (!biometricSet) {
await this.biometricStateService.setBiometricUnlockEnabled(false);
}
} finally {
this.messagingService.send("redrawMenu");
}
}
async updateAutoPromptBiometrics() {
if (this.form.value.autoPromptBiometrics) {
// require password on start must be disabled if auto prompt biometrics is enabled
this.form.controls.requirePasswordOnStart.setValue(false);
await this.updateRequirePasswordOnStart();
await this.biometricStateService.setPromptAutomatically(true);
} else {
await this.biometricStateService.setPromptAutomatically(false);
}
}
async updateRequirePasswordOnStart() {
if (this.form.value.requirePasswordOnStart) {
// auto prompt biometrics must be disabled if require password on start is enabled
this.form.controls.autoPromptBiometrics.setValue(false);
await this.updateAutoPromptBiometrics();
await this.biometricStateService.setRequirePasswordOnStart(true);
} else {
await this.biometricStateService.setRequirePasswordOnStart(false);
}
await this.biometricStateService.setDismissedRequirePasswordOnStartCallout();
await this.cryptoService.refreshAdditionalKeys();
}
async saveFavicons() {
await this.domainSettingsService.setShowFavicons(this.form.value.enableFavicons);
this.messagingService.send("refreshCiphers");
}
async saveMinToTray() {
await this.desktopSettingsService.setMinimizeToTray(this.form.value.enableMinToTray);
}
async saveCloseToTray() {
if (this.requireEnableTray) {
this.form.controls.enableTray.setValue(true);
await this.desktopSettingsService.setTrayEnabled(this.form.value.enableTray);
}
await this.desktopSettingsService.setCloseToTray(this.form.value.enableCloseToTray);
}
async saveTray() {
if (
this.requireEnableTray &&
!this.form.value.enableTray &&
(this.form.value.startToTray || this.form.value.enableCloseToTray)
) {
const confirm = await this.dialogService.openSimpleDialog({
title: { key: "confirmTrayTitle" },
content: { key: "confirmTrayDesc" },
type: "warning",
});
if (confirm) {
this.form.controls.startToTray.setValue(false, { emitEvent: false });
await this.desktopSettingsService.setStartToTray(this.form.value.startToTray);
this.form.controls.enableCloseToTray.setValue(false, { emitEvent: false });
await this.desktopSettingsService.setCloseToTray(this.form.value.enableCloseToTray);
} else {
this.form.controls.enableTray.setValue(true);
}
return;
}
await this.desktopSettingsService.setTrayEnabled(this.form.value.enableTray);
// TODO: Ideally the DesktopSettingsService.trayEnabled$ could be subscribed to instead of using messaging.
this.messagingService.send(this.form.value.enableTray ? "showTray" : "removeTray");
}
async saveStartToTray() {
if (this.requireEnableTray) {
this.form.controls.enableTray.setValue(true);
await this.desktopSettingsService.setTrayEnabled(this.form.value.enableTray);
}
await this.desktopSettingsService.setStartToTray(this.form.value.startToTray);
}
async saveLocale() {
await this.i18nService.setLocale(this.form.value.locale);
}
async saveTheme() {
await this.themeStateService.setSelectedTheme(this.form.value.theme);
}
async saveMinOnCopyToClipboard() {
await this.stateService.setMinimizeOnCopyToClipboard(this.form.value.minimizeOnCopyToClipboard);
}
async saveClearClipboard() {
await this.autofillSettingsService.setClearClipboardDelay(this.form.value.clearClipboard);
}
async saveAlwaysShowDock() {
await this.desktopSettingsService.setAlwaysShowDock(this.form.value.alwaysShowDock);
}
async saveOpenAtLogin() {
await this.desktopSettingsService.setOpenAtLogin(this.form.value.openAtLogin);
// TODO: Ideally DesktopSettingsService.openAtLogin$ could be subscribed to directly rather than sending a message
this.messagingService.send(
this.form.value.openAtLogin ? "addOpenAtLogin" : "removeOpenAtLogin",
);
}
async saveBrowserIntegration() {
if (
ipc.platform.deviceType === DeviceType.MacOsDesktop &&
!this.platformUtilsService.isMacAppStore()
) {
await this.dialogService.openSimpleDialog({
title: { key: "browserIntegrationUnsupportedTitle" },
content: { key: "browserIntegrationMasOnlyDesc" },
acceptButtonText: { key: "ok" },
cancelButtonText: null,
type: "warning",
});
this.form.controls.enableBrowserIntegration.setValue(false);
return;
} else if (ipc.platform.isWindowsStore) {
await this.dialogService.openSimpleDialog({
title: { key: "browserIntegrationUnsupportedTitle" },
content: { key: "browserIntegrationWindowsStoreDesc" },
acceptButtonText: { key: "ok" },
cancelButtonText: null,
type: "warning",
});
this.form.controls.enableBrowserIntegration.setValue(false);
return;
} else if (ipc.platform.deviceType === DeviceType.LinuxDesktop) {
await this.dialogService.openSimpleDialog({
title: { key: "browserIntegrationUnsupportedTitle" },
content: { key: "browserIntegrationLinuxDesc" },
acceptButtonText: { key: "ok" },
cancelButtonText: null,
type: "warning",
});
this.form.controls.enableBrowserIntegration.setValue(false);
return;
}
await this.stateService.setEnableBrowserIntegration(this.form.value.enableBrowserIntegration);
const errorResult = await this.nativeMessagingManifestService.generate(
this.form.value.enableBrowserIntegration,
);
if (errorResult !== null) {
this.logService.error("Error in browser integration: " + errorResult);
await this.dialogService.openSimpleDialog({
title: { key: "browserIntegrationErrorTitle" },
content: { key: "browserIntegrationErrorDesc" },
acceptButtonText: { key: "ok" },
cancelButtonText: null,
type: "danger",
});
}
if (!this.form.value.enableBrowserIntegration) {
this.form.controls.enableBrowserIntegrationFingerprint.setValue(false);
// 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.saveBrowserIntegrationFingerprint();
}
}
async saveDdgBrowserIntegration() {
await this.desktopAutofillSettingsService.setEnableDuckDuckGoBrowserIntegration(
this.form.value.enableDuckDuckGoBrowserIntegration,
);
// Adding to cover users on a previous version of DDG
await this.stateService.setEnableDuckDuckGoBrowserIntegration(
this.form.value.enableDuckDuckGoBrowserIntegration,
);
if (!this.form.value.enableBrowserIntegration) {
await this.stateService.setDuckDuckGoSharedKey(null);
}
const errorResult = await this.nativeMessagingManifestService.generateDuckDuckGo(
this.form.value.enableDuckDuckGoBrowserIntegration,
);
if (errorResult !== null) {
this.logService.error("Error in DDG browser integration: " + errorResult);
await this.dialogService.openSimpleDialog({
title: { key: "browserIntegrationUnsupportedTitle" },
content: errorResult.message,
acceptButtonText: { key: "ok" },
cancelButtonText: null,
type: "warning",
});
}
}
async saveBrowserIntegrationFingerprint() {
await this.stateService.setEnableBrowserIntegrationFingerprint(
this.form.value.enableBrowserIntegrationFingerprint,
);
}
async saveHardwareAcceleration() {
await this.desktopSettingsService.setHardwareAcceleration(
this.form.value.enableHardwareAcceleration,
);
}
async updateApproveLoginRequests() {
await this.authRequestService.setAcceptAuthRequests(
this.form.value.approveLoginRequests,
this.currentUserId,
);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
get biometricText() {
switch (this.platformUtilsService.getDevice()) {
case DeviceType.MacOsDesktop:
return "unlockWithTouchId";
case DeviceType.WindowsDesktop:
return "unlockWithWindowsHello";
default:
throw new Error("Unsupported platform");
}
}
get autoPromptBiometricsText() {
switch (this.platformUtilsService.getDevice()) {
case DeviceType.MacOsDesktop:
return "autoPromptTouchId";
case DeviceType.WindowsDesktop:
return "autoPromptWindowsHello";
default:
throw new Error("Unsupported platform");
}
}
get additionalBiometricSettingsText() {
switch (this.platformUtilsService.getDevice()) {
case DeviceType.MacOsDesktop:
return "additionalTouchIdSettings";
case DeviceType.WindowsDesktop:
return "additionalWindowsHelloSettings";
default:
throw new Error("Unsupported platform");
}
}
}