1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-01 13:13:36 +01:00

[PM-6383] Migrate clearClipboard account setting to autofill settings service (#8022)

* migrate clearClipboard account setting to autofill settings state provider

* replace state service get/set clearClipboard with autofill settings service equivalents

* PR suggestions cleanup
This commit is contained in:
Jonathan Prusik 2024-02-23 13:52:13 -05:00 committed by GitHub
parent 38e40a0471
commit 34a8d9af86
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 365 additions and 61 deletions

View File

@ -18,6 +18,7 @@ import {
} from "../../auth/background/service-factories/auth-service.factory"; } from "../../auth/background/service-factories/auth-service.factory";
import { userVerificationServiceFactory } from "../../auth/background/service-factories/user-verification-service.factory"; import { userVerificationServiceFactory } from "../../auth/background/service-factories/user-verification-service.factory";
import { openUnlockPopout } from "../../auth/popup/utils/auth-popout-window"; import { openUnlockPopout } from "../../auth/popup/utils/auth-popout-window";
import { autofillSettingsServiceFactory } from "../../autofill/background/service_factories/autofill-settings-service.factory";
import { eventCollectionServiceFactory } from "../../background/service-factories/event-collection-service.factory"; import { eventCollectionServiceFactory } from "../../background/service-factories/event-collection-service.factory";
import { Account } from "../../models/account"; import { Account } from "../../models/account";
import { CachedServices } from "../../platform/background/service-factories/factory-options"; import { CachedServices } from "../../platform/background/service-factories/factory-options";
@ -104,11 +105,14 @@ export class ContextMenuClickedHandler {
stateServiceOptions: { stateServiceOptions: {
stateFactory: stateFactory, stateFactory: stateFactory,
}, },
autofillSettingsServiceOptions: {
stateFactory: autofillSettingsServiceFactory,
},
}; };
const generatePasswordToClipboardCommand = new GeneratePasswordToClipboardCommand( const generatePasswordToClipboardCommand = new GeneratePasswordToClipboardCommand(
await passwordGenerationServiceFactory(cachedServices, serviceOptions), await passwordGenerationServiceFactory(cachedServices, serviceOptions),
await stateServiceFactory(cachedServices, serviceOptions), await autofillSettingsServiceFactory(cachedServices, serviceOptions),
); );
const autofillCommand = new AutofillTabCommand( const autofillCommand = new AutofillTabCommand(

View File

@ -1,10 +1,10 @@
import { mock, MockProxy } from "jest-mock-extended"; import { mock, MockProxy } from "jest-mock-extended";
import { AutofillSettingsService } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
import { setAlarmTime } from "../../platform/alarms/alarm-state"; import { setAlarmTime } from "../../platform/alarms/alarm-state";
import { BrowserApi } from "../../platform/browser/browser-api"; import { BrowserApi } from "../../platform/browser/browser-api";
import { BrowserStateService } from "../../platform/services/abstractions/browser-state.service";
import { clearClipboardAlarmName } from "./clear-clipboard"; import { clearClipboardAlarmName } from "./clear-clipboard";
import { GeneratePasswordToClipboardCommand } from "./generate-password-to-clipboard-command"; import { GeneratePasswordToClipboardCommand } from "./generate-password-to-clipboard-command";
@ -19,13 +19,12 @@ const setAlarmTimeMock = setAlarmTime as jest.Mock;
describe("GeneratePasswordToClipboardCommand", () => { describe("GeneratePasswordToClipboardCommand", () => {
let passwordGenerationService: MockProxy<PasswordGenerationServiceAbstraction>; let passwordGenerationService: MockProxy<PasswordGenerationServiceAbstraction>;
let stateService: MockProxy<BrowserStateService>; let autofillSettingsService: MockProxy<AutofillSettingsService>;
let sut: GeneratePasswordToClipboardCommand; let sut: GeneratePasswordToClipboardCommand;
beforeEach(() => { beforeEach(() => {
passwordGenerationService = mock<PasswordGenerationServiceAbstraction>(); passwordGenerationService = mock<PasswordGenerationServiceAbstraction>();
stateService = mock<BrowserStateService>();
passwordGenerationService.getOptions.mockResolvedValue([{ length: 8 }, {} as any]); passwordGenerationService.getOptions.mockResolvedValue([{ length: 8 }, {} as any]);
@ -33,7 +32,10 @@ describe("GeneratePasswordToClipboardCommand", () => {
jest.spyOn(BrowserApi, "sendTabsMessage").mockReturnValue(); jest.spyOn(BrowserApi, "sendTabsMessage").mockReturnValue();
sut = new GeneratePasswordToClipboardCommand(passwordGenerationService, stateService); sut = new GeneratePasswordToClipboardCommand(
passwordGenerationService,
autofillSettingsService,
);
}); });
afterEach(() => { afterEach(() => {
@ -42,7 +44,7 @@ describe("GeneratePasswordToClipboardCommand", () => {
describe("generatePasswordToClipboard", () => { describe("generatePasswordToClipboard", () => {
it("has clear clipboard value", async () => { it("has clear clipboard value", async () => {
stateService.getClearClipboard.mockResolvedValue(5 * 60); // 5 minutes jest.spyOn(sut as any, "getClearClipboard").mockImplementation(() => 5 * 60); // 5 minutes
await sut.generatePasswordToClipboard({ id: 1 } as any); await sut.generatePasswordToClipboard({ id: 1 } as any);
@ -59,7 +61,7 @@ describe("GeneratePasswordToClipboardCommand", () => {
}); });
it("does not have clear clipboard value", async () => { it("does not have clear clipboard value", async () => {
stateService.getClearClipboard.mockResolvedValue(null); jest.spyOn(sut as any, "getClearClipboard").mockImplementation(() => null);
await sut.generatePasswordToClipboard({ id: 1 } as any); await sut.generatePasswordToClipboard({ id: 1 } as any);

View File

@ -1,7 +1,9 @@
import { firstValueFrom } from "rxjs";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
import { setAlarmTime } from "../../platform/alarms/alarm-state"; import { setAlarmTime } from "../../platform/alarms/alarm-state";
import { BrowserStateService } from "../../platform/services/abstractions/browser-state.service";
import { clearClipboardAlarmName } from "./clear-clipboard"; import { clearClipboardAlarmName } from "./clear-clipboard";
import { copyToClipboard } from "./copy-to-clipboard-command"; import { copyToClipboard } from "./copy-to-clipboard-command";
@ -9,9 +11,13 @@ import { copyToClipboard } from "./copy-to-clipboard-command";
export class GeneratePasswordToClipboardCommand { export class GeneratePasswordToClipboardCommand {
constructor( constructor(
private passwordGenerationService: PasswordGenerationServiceAbstraction, private passwordGenerationService: PasswordGenerationServiceAbstraction,
private stateService: BrowserStateService, private autofillSettingsService: AutofillSettingsServiceAbstraction,
) {} ) {}
async getClearClipboard() {
return await firstValueFrom(this.autofillSettingsService.clearClipboardDelay$);
}
async generatePasswordToClipboard(tab: chrome.tabs.Tab) { async generatePasswordToClipboard(tab: chrome.tabs.Tab) {
const [options] = await this.passwordGenerationService.getOptions(); const [options] = await this.passwordGenerationService.getOptions();
const password = await this.passwordGenerationService.generatePassword(options); const password = await this.passwordGenerationService.generatePassword(options);
@ -20,7 +26,7 @@ export class GeneratePasswordToClipboardCommand {
// eslint-disable-next-line @typescript-eslint/no-floating-promises // eslint-disable-next-line @typescript-eslint/no-floating-promises
copyToClipboard(tab, password); copyToClipboard(tab, password);
const clearClipboard = await this.stateService.getClearClipboard(); const clearClipboard = await this.getClearClipboard();
if (clearClipboard != null) { if (clearClipboard != null) {
await setAlarmTime(clearClipboardAlarmName, clearClipboard * 1000); await setAlarmTime(clearClipboardAlarmName, clearClipboard * 1000);

View File

@ -22,6 +22,19 @@ export const EVENTS = {
FOCUSOUT: "focusout", FOCUSOUT: "focusout",
} as const; } as const;
export const ClearClipboardDelay = {
Never: null as null,
TenSeconds: 10,
TwentySeconds: 20,
ThirtySeconds: 30,
OneMinute: 60,
TwoMinutes: 120,
FiveMinutes: 300,
} as const;
export type ClearClipboardDelaySetting =
(typeof ClearClipboardDelay)[keyof typeof ClearClipboardDelay];
/* Context Menu item Ids */ /* Context Menu item Ids */
export const AUTOFILL_CARD_ID = "autofill-card"; export const AUTOFILL_CARD_ID = "autofill-card";
export const AUTOFILL_ID = "autofill"; export const AUTOFILL_ID = "autofill";

View File

@ -779,6 +779,7 @@ export default class MainBackground {
this.platformUtilsService, this.platformUtilsService,
systemUtilsServiceReloadCallback, systemUtilsServiceReloadCallback,
this.stateService, this.stateService,
this.autofillSettingsService,
this.vaultTimeoutSettingsService, this.vaultTimeoutSettingsService,
); );

View File

@ -4,10 +4,10 @@ import { GlobalState } from "@bitwarden/common/platform/models/domain/global-sta
import { authServiceFactory } from "../../auth/background/service-factories/auth-service.factory"; import { authServiceFactory } from "../../auth/background/service-factories/auth-service.factory";
import { autofillServiceFactory } from "../../autofill/background/service_factories/autofill-service.factory"; import { autofillServiceFactory } from "../../autofill/background/service_factories/autofill-service.factory";
import { autofillSettingsServiceFactory } from "../../autofill/background/service_factories/autofill-settings-service.factory";
import { GeneratePasswordToClipboardCommand } from "../../autofill/clipboard"; import { GeneratePasswordToClipboardCommand } from "../../autofill/clipboard";
import { AutofillTabCommand } from "../../autofill/commands/autofill-tab-command"; import { AutofillTabCommand } from "../../autofill/commands/autofill-tab-command";
import { Account } from "../../models/account"; import { Account } from "../../models/account";
import { stateServiceFactory } from "../../platform/background/service-factories/state-service.factory";
import { import {
passwordGenerationServiceFactory, passwordGenerationServiceFactory,
PasswordGenerationServiceInitOptions, PasswordGenerationServiceInitOptions,
@ -94,11 +94,14 @@ const doGeneratePasswordToClipboard = async (tab: chrome.tabs.Tab): Promise<void
stateServiceOptions: { stateServiceOptions: {
stateFactory: stateFactory, stateFactory: stateFactory,
}, },
autofillSettingsServiceOptions: {
stateFactory: autofillSettingsServiceFactory,
},
}; };
const command = new GeneratePasswordToClipboardCommand( const command = new GeneratePasswordToClipboardCommand(
await passwordGenerationServiceFactory(cache, options), await passwordGenerationServiceFactory(cache, options),
await stateServiceFactory(cache, options), await autofillSettingsServiceFactory(cache, options),
); );
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. // 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 // eslint-disable-next-line @typescript-eslint/no-floating-promises

View File

@ -11,6 +11,7 @@ import { ThemeType } from "@bitwarden/common/platform/enums";
import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service"; import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
import { UriMatchType } from "@bitwarden/common/vault/enums"; import { UriMatchType } from "@bitwarden/common/vault/enums";
import { ClearClipboardDelaySetting } from "../../../../../apps/browser/src/autofill/constants";
import { enableAccountSwitching } from "../../platform/flags"; import { enableAccountSwitching } from "../../platform/flags";
@Component({ @Component({
@ -35,7 +36,7 @@ export class OptionsComponent implements OnInit {
themeOptions: any[]; themeOptions: any[];
defaultUriMatch = UriMatchType.Domain; defaultUriMatch = UriMatchType.Domain;
uriMatchOptions: any[]; uriMatchOptions: any[];
clearClipboard: number; clearClipboard: ClearClipboardDelaySetting;
clearClipboardOptions: any[]; clearClipboardOptions: any[];
showGeneral = true; showGeneral = true;
showAutofill = true; showAutofill = true;
@ -115,7 +116,7 @@ export class OptionsComponent implements OnInit {
const defaultUriMatch = await this.stateService.getDefaultUriMatch(); const defaultUriMatch = await this.stateService.getDefaultUriMatch();
this.defaultUriMatch = defaultUriMatch == null ? UriMatchType.Domain : defaultUriMatch; this.defaultUriMatch = defaultUriMatch == null ? UriMatchType.Domain : defaultUriMatch;
this.clearClipboard = await this.stateService.getClearClipboard(); this.clearClipboard = await firstValueFrom(this.autofillSettingsService.clearClipboardDelay$);
} }
async updateAddLoginNotification() { async updateAddLoginNotification() {
@ -175,6 +176,6 @@ export class OptionsComponent implements OnInit {
} }
async saveClearClipboard() { async saveClearClipboard() {
await this.stateService.setClearClipboard(this.clearClipboard); await this.autofillSettingsService.setClearClipboardDelay(this.clearClipboard);
} }
} }

View File

@ -10,6 +10,7 @@ import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vaul
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { UserVerificationService as UserVerificationServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; 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 { DeviceType } from "@bitwarden/common/enums"; import { DeviceType } from "@bitwarden/common/enums";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
@ -81,7 +82,7 @@ export class SettingsComponent implements OnInit {
requirePasswordOnStart: false, requirePasswordOnStart: false,
approveLoginRequests: false, approveLoginRequests: false,
// Account Preferences // Account Preferences
clearClipboard: [null as number | null], clearClipboard: [null],
minimizeOnCopyToClipboard: false, minimizeOnCopyToClipboard: false,
enableFavicons: false, enableFavicons: false,
// App Settings // App Settings
@ -111,6 +112,7 @@ export class SettingsComponent implements OnInit {
private platformUtilsService: PlatformUtilsService, private platformUtilsService: PlatformUtilsService,
private vaultTimeoutSettingsService: VaultTimeoutSettingsService, private vaultTimeoutSettingsService: VaultTimeoutSettingsService,
private stateService: StateService, private stateService: StateService,
private autofillSettingsService: AutofillSettingsServiceAbstraction,
private messagingService: MessagingService, private messagingService: MessagingService,
private cryptoService: CryptoService, private cryptoService: CryptoService,
private modalService: ModalService, private modalService: ModalService,
@ -247,7 +249,7 @@ export class SettingsComponent implements OnInit {
this.biometricStateService.requirePasswordOnStart$, this.biometricStateService.requirePasswordOnStart$,
), ),
approveLoginRequests: (await this.stateService.getApproveLoginRequests()) ?? false, approveLoginRequests: (await this.stateService.getApproveLoginRequests()) ?? false,
clearClipboard: await this.stateService.getClearClipboard(), clearClipboard: await firstValueFrom(this.autofillSettingsService.clearClipboardDelay$),
minimizeOnCopyToClipboard: await this.stateService.getMinimizeOnCopyToClipboard(), minimizeOnCopyToClipboard: await this.stateService.getMinimizeOnCopyToClipboard(),
enableFavicons: !(await this.stateService.getDisableFavicon()), enableFavicons: !(await this.stateService.getDisableFavicon()),
enableTray: await this.stateService.getEnableTray(), enableTray: await this.stateService.getEnableTray(),
@ -563,7 +565,7 @@ export class SettingsComponent implements OnInit {
} }
async saveClearClipboard() { async saveClearClipboard() {
await this.stateService.setClearClipboard(this.form.value.clearClipboard); await this.autofillSettingsService.setClearClipboardDelay(this.form.value.clearClipboard);
} }
async saveAlwaysShowDock() { async saveAlwaysShowDock() {

View File

@ -1,5 +1,9 @@
import { filter, switchMap, tap, firstValueFrom, map, Observable } from "rxjs"; import { filter, switchMap, tap, firstValueFrom, map, Observable } from "rxjs";
import {
ClearClipboardDelaySetting,
ClearClipboardDelay,
} from "../../../../../apps/browser/src/autofill/constants";
import { import {
AutofillOverlayVisibility, AutofillOverlayVisibility,
InlineMenuVisibilitySetting, InlineMenuVisibilitySetting,
@ -56,6 +60,14 @@ const INLINE_MENU_VISIBILITY = new KeyDefinition(
}, },
); );
const CLEAR_CLIPBOARD_DELAY = new KeyDefinition(
AUTOFILL_SETTINGS_DISK_LOCAL,
"clearClipboardDelay",
{
deserializer: (value: ClearClipboardDelaySetting) => value ?? ClearClipboardDelay.Never,
},
);
export abstract class AutofillSettingsServiceAbstraction { export abstract class AutofillSettingsServiceAbstraction {
autofillOnPageLoad$: Observable<boolean>; autofillOnPageLoad$: Observable<boolean>;
setAutofillOnPageLoad: (newValue: boolean) => Promise<void>; setAutofillOnPageLoad: (newValue: boolean) => Promise<void>;
@ -69,6 +81,8 @@ export abstract class AutofillSettingsServiceAbstraction {
setActivateAutofillOnPageLoadFromPolicy: (newValue: boolean) => Promise<void>; setActivateAutofillOnPageLoadFromPolicy: (newValue: boolean) => Promise<void>;
inlineMenuVisibility$: Observable<InlineMenuVisibilitySetting>; inlineMenuVisibility$: Observable<InlineMenuVisibilitySetting>;
setInlineMenuVisibility: (newValue: InlineMenuVisibilitySetting) => Promise<void>; setInlineMenuVisibility: (newValue: InlineMenuVisibilitySetting) => Promise<void>;
clearClipboardDelay$: Observable<ClearClipboardDelaySetting>;
setClearClipboardDelay: (newValue: ClearClipboardDelaySetting) => Promise<void>;
handleActivateAutofillPolicy: (policies: Observable<Policy[]>) => Observable<boolean[]>; handleActivateAutofillPolicy: (policies: Observable<Policy[]>) => Observable<boolean[]>;
} }
@ -91,6 +105,9 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
private inlineMenuVisibilityState: GlobalState<InlineMenuVisibilitySetting>; private inlineMenuVisibilityState: GlobalState<InlineMenuVisibilitySetting>;
readonly inlineMenuVisibility$: Observable<InlineMenuVisibilitySetting>; readonly inlineMenuVisibility$: Observable<InlineMenuVisibilitySetting>;
private clearClipboardDelayState: ActiveUserState<ClearClipboardDelaySetting>;
readonly clearClipboardDelay$: Observable<ClearClipboardDelaySetting>;
constructor( constructor(
private stateProvider: StateProvider, private stateProvider: StateProvider,
policyService: PolicyService, policyService: PolicyService,
@ -125,6 +142,11 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
map((x) => x ?? AutofillOverlayVisibility.Off), map((x) => x ?? AutofillOverlayVisibility.Off),
); );
this.clearClipboardDelayState = this.stateProvider.getActive(CLEAR_CLIPBOARD_DELAY);
this.clearClipboardDelay$ = this.clearClipboardDelayState.state$.pipe(
map((x) => x ?? ClearClipboardDelay.Never),
);
policyService.policies$.pipe(this.handleActivateAutofillPolicy.bind(this)).subscribe(); policyService.policies$.pipe(this.handleActivateAutofillPolicy.bind(this)).subscribe();
} }
@ -152,6 +174,10 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
await this.inlineMenuVisibilityState.update(() => newValue); await this.inlineMenuVisibilityState.update(() => newValue);
} }
async setClearClipboardDelay(newValue: ClearClipboardDelaySetting): Promise<void> {
await this.clearClipboardDelayState.update(() => newValue);
}
/** /**
* If the ActivateAutofill policy is enabled, save a flag indicating if we need to * If the ActivateAutofill policy is enabled, save a flag indicating if we need to
* enable Autofill on page load. * enable Autofill on page load.

View File

@ -81,8 +81,6 @@ export abstract class StateService<T extends Account = Account> {
setHasPremiumPersonally: (value: boolean, options?: StorageOptions) => Promise<void>; setHasPremiumPersonally: (value: boolean, options?: StorageOptions) => Promise<void>;
setHasPremiumFromOrganization: (value: boolean, options?: StorageOptions) => Promise<void>; setHasPremiumFromOrganization: (value: boolean, options?: StorageOptions) => Promise<void>;
getHasPremiumFromOrganization: (options?: StorageOptions) => Promise<boolean>; getHasPremiumFromOrganization: (options?: StorageOptions) => Promise<boolean>;
getClearClipboard: (options?: StorageOptions) => Promise<number>;
setClearClipboard: (value: number, options?: StorageOptions) => Promise<void>;
getConvertAccountToKeyConnector: (options?: StorageOptions) => Promise<boolean>; getConvertAccountToKeyConnector: (options?: StorageOptions) => Promise<boolean>;
setConvertAccountToKeyConnector: (value: boolean, options?: StorageOptions) => Promise<void>; setConvertAccountToKeyConnector: (value: boolean, options?: StorageOptions) => Promise<void>;
/** /**

View File

@ -201,7 +201,6 @@ export class AccountProfile {
export class AccountSettings { export class AccountSettings {
autoConfirmFingerPrints?: boolean; autoConfirmFingerPrints?: boolean;
biometricUnlock?: boolean; biometricUnlock?: boolean;
clearClipboard?: number;
defaultUriMatch?: UriMatchType; defaultUriMatch?: UriMatchType;
disableBadgeCounter?: boolean; disableBadgeCounter?: boolean;
disableGa?: boolean; disableGa?: boolean;

View File

@ -462,27 +462,6 @@ export class StateService<
); );
} }
async getClearClipboard(options?: StorageOptions): Promise<number> {
return (
(
await this.getAccount(
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
)
)?.settings?.clearClipboard ?? null
);
}
async setClearClipboard(value: number, options?: StorageOptions): Promise<void> {
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
);
account.settings.clearClipboard = value;
await this.saveAccount(
account,
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
);
}
async getConvertAccountToKeyConnector(options?: StorageOptions): Promise<boolean> { async getConvertAccountToKeyConnector(options?: StorageOptions): Promise<boolean> {
return ( return (
await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions())) await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions()))

View File

@ -3,6 +3,7 @@ import { firstValueFrom, timeout } from "rxjs";
import { VaultTimeoutSettingsService } from "../../abstractions/vault-timeout/vault-timeout-settings.service"; import { VaultTimeoutSettingsService } from "../../abstractions/vault-timeout/vault-timeout-settings.service";
import { AuthService } from "../../auth/abstractions/auth.service"; import { AuthService } from "../../auth/abstractions/auth.service";
import { AuthenticationStatus } from "../../auth/enums/authentication-status"; import { AuthenticationStatus } from "../../auth/enums/authentication-status";
import { AutofillSettingsServiceAbstraction } from "../../autofill/services/autofill-settings.service";
import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum";
import { MessagingService } from "../abstractions/messaging.service"; import { MessagingService } from "../abstractions/messaging.service";
import { PlatformUtilsService } from "../abstractions/platform-utils.service"; import { PlatformUtilsService } from "../abstractions/platform-utils.service";
@ -20,6 +21,7 @@ export class SystemService implements SystemServiceAbstraction {
private platformUtilsService: PlatformUtilsService, private platformUtilsService: PlatformUtilsService,
private reloadCallback: () => Promise<void> = null, private reloadCallback: () => Promise<void> = null,
private stateService: StateService, private stateService: StateService,
private autofillSettingsService: AutofillSettingsServiceAbstraction,
private vaultTimeoutSettingsService: VaultTimeoutSettingsService, private vaultTimeoutSettingsService: VaultTimeoutSettingsService,
) {} ) {}
@ -93,26 +95,33 @@ export class SystemService implements SystemServiceAbstraction {
clearTimeout(this.clearClipboardTimeout); clearTimeout(this.clearClipboardTimeout);
this.clearClipboardTimeout = null; this.clearClipboardTimeout = null;
} }
if (Utils.isNullOrWhitespace(clipboardValue)) { if (Utils.isNullOrWhitespace(clipboardValue)) {
return; return;
} }
await this.stateService.getClearClipboard().then((clearSeconds) => {
if (clearSeconds == null) { const clearClipboardDelay = await firstValueFrom(
this.autofillSettingsService.clearClipboardDelay$,
);
if (clearClipboardDelay == null) {
return; return;
} }
if (timeoutMs == null) { if (timeoutMs == null) {
timeoutMs = clearSeconds * 1000; timeoutMs = clearClipboardDelay * 1000;
} }
this.clearClipboardTimeoutFunction = async () => { this.clearClipboardTimeoutFunction = async () => {
const clipboardValueNow = await this.platformUtilsService.readFromClipboard(); const clipboardValueNow = await this.platformUtilsService.readFromClipboard();
if (clipboardValue === clipboardValueNow) { if (clipboardValue === clipboardValueNow) {
this.platformUtilsService.copyToClipboard("", { clearing: true }); this.platformUtilsService.copyToClipboard("", { clearing: true });
} }
}; };
this.clearClipboardTimeout = setTimeout(async () => { this.clearClipboardTimeout = setTimeout(async () => {
await this.clearPendingClipboard(); await this.clearPendingClipboard();
}, timeoutMs); }, timeoutMs);
});
} }
async clearPendingClipboard() { async clearPendingClipboard() {

View File

@ -19,6 +19,7 @@ import { CollectionMigrator } from "./migrations/21-move-collections-state-to-st
import { CollapsedGroupingsMigrator } from "./migrations/22-move-collapsed-groupings-to-state-provider"; import { CollapsedGroupingsMigrator } from "./migrations/22-move-collapsed-groupings-to-state-provider";
import { MoveBiometricPromptsToStateProviders } from "./migrations/23-move-biometric-prompts-to-state-providers"; import { MoveBiometricPromptsToStateProviders } from "./migrations/23-move-biometric-prompts-to-state-providers";
import { SmOnboardingTasksMigrator } from "./migrations/24-move-sm-onboarding-key-to-state-providers"; import { SmOnboardingTasksMigrator } from "./migrations/24-move-sm-onboarding-key-to-state-providers";
import { ClearClipboardDelayMigrator } from "./migrations/25-move-clear-clipboard-to-autofill-settings-state-provider";
import { FixPremiumMigrator } from "./migrations/3-fix-premium"; import { FixPremiumMigrator } from "./migrations/3-fix-premium";
import { RemoveEverBeenUnlockedMigrator } from "./migrations/4-remove-ever-been-unlocked"; import { RemoveEverBeenUnlockedMigrator } from "./migrations/4-remove-ever-been-unlocked";
import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys"; import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys";
@ -29,7 +30,7 @@ import { MoveBrowserSettingsToGlobal } from "./migrations/9-move-browser-setting
import { MinVersionMigrator } from "./migrations/min-version"; import { MinVersionMigrator } from "./migrations/min-version";
export const MIN_VERSION = 2; export const MIN_VERSION = 2;
export const CURRENT_VERSION = 24; export const CURRENT_VERSION = 25;
export type MinVersion = typeof MIN_VERSION; export type MinVersion = typeof MIN_VERSION;
export function createMigrationBuilder() { export function createMigrationBuilder() {
@ -56,7 +57,8 @@ export function createMigrationBuilder() {
.with(CollectionMigrator, 20, 21) .with(CollectionMigrator, 20, 21)
.with(CollapsedGroupingsMigrator, 21, 22) .with(CollapsedGroupingsMigrator, 21, 22)
.with(MoveBiometricPromptsToStateProviders, 22, 23) .with(MoveBiometricPromptsToStateProviders, 22, 23)
.with(SmOnboardingTasksMigrator, 23, CURRENT_VERSION); .with(SmOnboardingTasksMigrator, 23, 24)
.with(ClearClipboardDelayMigrator, 24, CURRENT_VERSION);
} }
export async function currentVersion( export async function currentVersion(

View File

@ -1,11 +1,16 @@
import { any, MockProxy } from "jest-mock-extended"; import { any, MockProxy } from "jest-mock-extended";
import { AutofillOverlayVisibility } from "../../../../../apps/browser/src/autofill/utils/autofill-overlay.enum";
import { StateDefinitionLike, MigrationHelper } from "../migration-helper"; import { StateDefinitionLike, MigrationHelper } from "../migration-helper";
import { mockMigrationHelper } from "../migration-helper.spec"; import { mockMigrationHelper } from "../migration-helper.spec";
import { AutofillSettingsKeyMigrator } from "./18-move-autofill-settings-to-state-providers"; import { AutofillSettingsKeyMigrator } from "./18-move-autofill-settings-to-state-providers";
const AutofillOverlayVisibility = {
Off: 0,
OnButtonClick: 1,
OnFieldFocus: 2,
} as const;
function exampleJSON() { function exampleJSON() {
return { return {
global: { global: {

View File

@ -0,0 +1,177 @@
import { any, MockProxy } from "jest-mock-extended";
import { StateDefinitionLike, MigrationHelper } from "../migration-helper";
import { mockMigrationHelper } from "../migration-helper.spec";
import { ClearClipboardDelayMigrator } from "./25-move-clear-clipboard-to-autofill-settings-state-provider";
export const ClearClipboardDelay = {
Never: null as null,
TenSeconds: 10,
TwentySeconds: 20,
ThirtySeconds: 30,
OneMinute: 60,
TwoMinutes: 120,
FiveMinutes: 300,
} as const;
const AutofillOverlayVisibility = {
Off: 0,
OnButtonClick: 1,
OnFieldFocus: 2,
} as const;
function exampleJSON() {
return {
global: {
otherStuff: "otherStuff1",
},
authenticatedAccounts: ["user-1", "user-2", "user-3"],
"user-1": {
settings: {
clearClipboard: ClearClipboardDelay.TenSeconds,
otherStuff: "otherStuff2",
},
otherStuff: "otherStuff3",
},
"user-2": {
settings: {
clearClipboard: ClearClipboardDelay.Never,
otherStuff: "otherStuff4",
},
otherStuff: "otherStuff5",
},
"user-3": {
settings: {
otherStuff: "otherStuff4",
},
otherStuff: "otherStuff5",
},
};
}
function rollbackJSON() {
return {
global_autofillSettingsLocal_inlineMenuVisibility: AutofillOverlayVisibility.OnButtonClick,
"user_user-1_autofillSettingsLocal_clearClipboardDelay": ClearClipboardDelay.TenSeconds,
"user_user-2_autofillSettingsLocal_clearClipboardDelay": ClearClipboardDelay.Never,
global: {
otherStuff: "otherStuff1",
},
authenticatedAccounts: ["user-1", "user-2", "user-3"],
"user-1": {
settings: {
otherStuff: "otherStuff2",
},
otherStuff: "otherStuff3",
},
"user-2": {
settings: {
otherStuff: "otherStuff4",
},
otherStuff: "otherStuff5",
},
};
}
const autofillSettingsLocalStateDefinition: {
stateDefinition: StateDefinitionLike;
} = {
stateDefinition: {
name: "autofillSettingsLocal",
},
};
describe("ProviderKeysMigrator", () => {
let helper: MockProxy<MigrationHelper>;
let sut: ClearClipboardDelayMigrator;
describe("migrate", () => {
beforeEach(() => {
helper = mockMigrationHelper(exampleJSON(), 24);
sut = new ClearClipboardDelayMigrator(24, 25);
});
it("should remove clearClipboard setting from all accounts", async () => {
await sut.migrate(helper);
expect(helper.set).toHaveBeenCalledTimes(2);
expect(helper.set).toHaveBeenCalledWith("user-1", {
settings: {
otherStuff: "otherStuff2",
},
otherStuff: "otherStuff3",
});
expect(helper.set).toHaveBeenCalledWith("user-2", {
settings: {
otherStuff: "otherStuff4",
},
otherStuff: "otherStuff5",
});
});
it("should set autofill setting values for each account", async () => {
await sut.migrate(helper);
expect(helper.setToUser).toHaveBeenCalledTimes(2);
expect(helper.setToUser).toHaveBeenCalledWith(
"user-1",
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
ClearClipboardDelay.TenSeconds,
);
expect(helper.setToUser).toHaveBeenCalledWith(
"user-2",
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
ClearClipboardDelay.Never,
);
});
});
describe("rollback", () => {
beforeEach(() => {
helper = mockMigrationHelper(rollbackJSON(), 23);
sut = new ClearClipboardDelayMigrator(24, 25);
});
it("should null out new values for each account", async () => {
await sut.rollback(helper);
expect(helper.setToUser).toHaveBeenCalledTimes(2);
expect(helper.setToUser).toHaveBeenCalledWith(
"user-1",
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
null,
);
expect(helper.setToUser).toHaveBeenCalledWith(
"user-2",
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
null,
);
});
it("should add explicit value back to accounts", async () => {
await sut.rollback(helper);
expect(helper.set).toHaveBeenCalledTimes(2);
expect(helper.set).toHaveBeenCalledWith("user-1", {
settings: {
clearClipboard: ClearClipboardDelay.TenSeconds,
otherStuff: "otherStuff2",
},
otherStuff: "otherStuff3",
});
expect(helper.set).toHaveBeenCalledWith("user-2", {
settings: {
clearClipboard: ClearClipboardDelay.Never,
otherStuff: "otherStuff4",
},
otherStuff: "otherStuff5",
});
});
it("should not try to restore values to missing accounts", async () => {
await sut.rollback(helper);
expect(helper.set).not.toHaveBeenCalledWith("user-3", any());
});
});
});

View File

@ -0,0 +1,77 @@
import { ClearClipboardDelaySetting } from "../../../../../apps/browser/src/autofill/constants";
import { StateDefinitionLike, MigrationHelper } from "../migration-helper";
import { Migrator } from "../migrator";
type ExpectedAccountState = {
settings?: {
clearClipboard?: ClearClipboardDelaySetting;
};
};
const autofillSettingsLocalStateDefinition: {
stateDefinition: StateDefinitionLike;
} = {
stateDefinition: {
name: "autofillSettingsLocal",
},
};
export class ClearClipboardDelayMigrator extends Migrator<24, 25> {
async migrate(helper: MigrationHelper): Promise<void> {
// account state (e.g. account settings -> state provider framework keys)
const accounts = await helper.getAccounts<ExpectedAccountState>();
await Promise.all([...accounts.map(({ userId, account }) => migrateAccount(userId, account))]);
// migrate account state
async function migrateAccount(userId: string, account: ExpectedAccountState): Promise<void> {
const accountSettings = account?.settings;
if (accountSettings?.clearClipboard !== undefined) {
await helper.setToUser(
userId,
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
accountSettings.clearClipboard,
);
delete account.settings.clearClipboard;
// update the state account settings with the migrated values deleted
await helper.set(userId, account);
}
}
}
async rollback(helper: MigrationHelper): Promise<void> {
// account state (e.g. state provider framework keys -> account settings)
const accounts = await helper.getAccounts<ExpectedAccountState>();
await Promise.all([...accounts.map(({ userId, account }) => rollbackAccount(userId, account))]);
// rollback account state
async function rollbackAccount(userId: string, account: ExpectedAccountState): Promise<void> {
let settings = account?.settings || {};
const clearClipboardDelay: ClearClipboardDelaySetting = await helper.getFromUser(userId, {
...autofillSettingsLocalStateDefinition,
key: "clearClipboardDelay",
});
// update new settings and remove the account state provider framework keys for the rolled back values
if (clearClipboardDelay !== undefined) {
settings = { ...settings, clearClipboard: clearClipboardDelay };
await helper.setToUser(
userId,
{ ...autofillSettingsLocalStateDefinition, key: "clearClipboardDelay" },
null,
);
// commit updated settings to state
await helper.set(userId, {
...account,
settings,
});
}
}
}
}