1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-14 10:26:19 +01:00

[PM-10744] Remove Last Uses of getBgService (#10947)

* Remove Last Uses of `getBgService`

* Fix Merge Issue

* Fix Merge
This commit is contained in:
Justin Baur 2024-11-04 15:10:36 -05:00 committed by GitHub
parent fc9c10340b
commit 008e928d0a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 262 additions and 334 deletions

View File

@ -257,12 +257,9 @@ import { BrowserPlatformUtilsService } from "../platform/services/platform-utils
import { PopupViewCacheBackgroundService } from "../platform/services/popup-view-cache-background.service"; import { PopupViewCacheBackgroundService } from "../platform/services/popup-view-cache-background.service";
import { BrowserSdkClientFactory } from "../platform/services/sdk/browser-sdk-client-factory"; import { BrowserSdkClientFactory } from "../platform/services/sdk/browser-sdk-client-factory";
import { BackgroundTaskSchedulerService } from "../platform/services/task-scheduler/background-task-scheduler.service"; import { BackgroundTaskSchedulerService } from "../platform/services/task-scheduler/background-task-scheduler.service";
import { ForegroundTaskSchedulerService } from "../platform/services/task-scheduler/foreground-task-scheduler.service";
import { BackgroundMemoryStorageService } from "../platform/storage/background-memory-storage.service"; import { BackgroundMemoryStorageService } from "../platform/storage/background-memory-storage.service";
import { BrowserStorageServiceProvider } from "../platform/storage/browser-storage-service.provider"; import { BrowserStorageServiceProvider } from "../platform/storage/browser-storage-service.provider";
import { ForegroundMemoryStorageService } from "../platform/storage/foreground-memory-storage.service";
import { OffscreenStorageService } from "../platform/storage/offscreen-storage.service"; import { OffscreenStorageService } from "../platform/storage/offscreen-storage.service";
import { ForegroundSyncService } from "../platform/sync/foreground-sync.service";
import { SyncServiceListener } from "../platform/sync/sync-service.listener"; import { SyncServiceListener } from "../platform/sync/sync-service.listener";
import { fromChromeRuntimeMessaging } from "../platform/utils/from-chrome-runtime-messaging"; import { fromChromeRuntimeMessaging } from "../platform/utils/from-chrome-runtime-messaging";
import VaultTimeoutService from "../services/vault-timeout/vault-timeout.service"; import VaultTimeoutService from "../services/vault-timeout/vault-timeout.service";
@ -401,7 +398,7 @@ export default class MainBackground {
private popupViewCacheBackgroundService: PopupViewCacheBackgroundService; private popupViewCacheBackgroundService: PopupViewCacheBackgroundService;
constructor(public popupOnlyContext: boolean = false) { constructor() {
// Services // Services
const lockedCallback = async (userId?: string) => { const lockedCallback = async (userId?: string) => {
if (this.notificationsService != null) { if (this.notificationsService != null) {
@ -460,45 +457,6 @@ export default class MainBackground {
this.offscreenDocumentService, this.offscreenDocumentService,
); );
// Creates a session key for mv3 storage of large memory items
const sessionKey = new Lazy(async () => {
// Key already in session storage
const sessionStorage = new BrowserMemoryStorageService();
const existingKey = await sessionStorage.get<SymmetricCryptoKey>("session-key");
if (existingKey) {
if (sessionStorage.valuesRequireDeserialization) {
return SymmetricCryptoKey.fromJSON(existingKey);
}
return existingKey;
}
// New key
const { derivedKey } = await this.keyGenerationService.createKeyWithPurpose(
128,
"ephemeral",
"bitwarden-ephemeral",
);
await sessionStorage.save("session-key", derivedKey);
return derivedKey;
});
const mv3MemoryStorageCreator = () => {
if (this.popupOnlyContext) {
return new ForegroundMemoryStorageService();
}
// For local backed session storage, we expect that the encrypted data on disk will persist longer than the encryption key in memory
// and failures to decrypt because of that are completely expected. For this reason, we pass in `false` to the `EncryptServiceImplementation`
// so that MAC failures are not logged.
return new LocalBackedSessionStorageService(
sessionKey,
this.storageService,
new EncryptServiceImplementation(this.cryptoFunctionService, this.logService, false),
this.platformUtilsService,
this.logService,
);
};
this.secureStorageService = this.storageService; // secure storage is not supported in browsers, so we use local storage and warn users when it is used this.secureStorageService = this.storageService; // secure storage is not supported in browsers, so we use local storage and warn users when it is used
if (BrowserApi.isManifestVersion(3)) { if (BrowserApi.isManifestVersion(3)) {
@ -506,18 +464,47 @@ export default class MainBackground {
this.memoryStorageForStateProviders = new BrowserMemoryStorageService(); // mv3 stores to storage.session this.memoryStorageForStateProviders = new BrowserMemoryStorageService(); // mv3 stores to storage.session
this.memoryStorageService = this.memoryStorageForStateProviders; this.memoryStorageService = this.memoryStorageForStateProviders;
} else { } else {
if (popupOnlyContext) { this.memoryStorageForStateProviders = new BackgroundMemoryStorageService(); // mv2 stores to memory
this.memoryStorageForStateProviders = new ForegroundMemoryStorageService(); this.memoryStorageService = this.memoryStorageForStateProviders;
this.memoryStorageService = new ForegroundMemoryStorageService();
} else {
this.memoryStorageForStateProviders = new BackgroundMemoryStorageService(); // mv2 stores to memory
this.memoryStorageService = this.memoryStorageForStateProviders;
}
} }
this.largeObjectMemoryStorageForStateProviders = BrowserApi.isManifestVersion(3) if (BrowserApi.isManifestVersion(3)) {
? mv3MemoryStorageCreator() // mv3 stores to local-backed session storage // Creates a session key for mv3 storage of large memory items
: this.memoryStorageForStateProviders; // mv2 stores to the same location const sessionKey = new Lazy(async () => {
// Key already in session storage
const sessionStorage = new BrowserMemoryStorageService();
const existingKey = await sessionStorage.get<SymmetricCryptoKey>("session-key");
if (existingKey) {
if (sessionStorage.valuesRequireDeserialization) {
return SymmetricCryptoKey.fromJSON(existingKey);
}
return existingKey;
}
// New key
const { derivedKey } = await this.keyGenerationService.createKeyWithPurpose(
128,
"ephemeral",
"bitwarden-ephemeral",
);
await sessionStorage.save("session-key", derivedKey);
return derivedKey;
});
this.largeObjectMemoryStorageForStateProviders = new LocalBackedSessionStorageService(
sessionKey,
this.storageService,
// For local backed session storage, we expect that the encrypted data on disk will persist longer than the encryption key in memory
// and failures to decrypt because of that are completely expected. For this reason, we pass in `false` to the `EncryptServiceImplementation`
// so that MAC failures are not logged.
new EncryptServiceImplementation(this.cryptoFunctionService, this.logService, false),
this.platformUtilsService,
this.logService,
);
} else {
// mv2 stores to the same location
this.largeObjectMemoryStorageForStateProviders = this.memoryStorageForStateProviders;
}
const localStorageStorageService = BrowserApi.isManifestVersion(3) const localStorageStorageService = BrowserApi.isManifestVersion(3)
? new OffscreenStorageService(this.offscreenDocumentService) ? new OffscreenStorageService(this.offscreenDocumentService)
@ -575,9 +562,10 @@ export default class MainBackground {
this.derivedStateProvider, this.derivedStateProvider,
); );
this.taskSchedulerService = this.popupOnlyContext this.taskSchedulerService = new BackgroundTaskSchedulerService(
? new ForegroundTaskSchedulerService(this.logService, this.stateProvider) this.logService,
: new BackgroundTaskSchedulerService(this.logService, this.stateProvider); this.stateProvider,
);
this.taskSchedulerService.registerTaskHandler(ScheduledTaskNames.scheduleNextSyncInterval, () => this.taskSchedulerService.registerTaskHandler(ScheduledTaskNames.scheduleNextSyncInterval, () =>
this.fullSync(), this.fullSync(),
); );
@ -873,26 +861,24 @@ export default class MainBackground {
this.vaultSettingsService = new VaultSettingsService(this.stateProvider); this.vaultSettingsService = new VaultSettingsService(this.stateProvider);
if (!this.popupOnlyContext) { this.vaultTimeoutService = new VaultTimeoutService(
this.vaultTimeoutService = new VaultTimeoutService( this.accountService,
this.accountService, this.masterPasswordService,
this.masterPasswordService, this.cipherService,
this.cipherService, this.folderService,
this.folderService, this.collectionService,
this.collectionService, this.platformUtilsService,
this.platformUtilsService, this.messagingService,
this.messagingService, this.searchService,
this.searchService, this.stateService,
this.stateService, this.authService,
this.authService, this.vaultTimeoutSettingsService,
this.vaultTimeoutSettingsService, this.stateEventRunnerService,
this.stateEventRunnerService, this.taskSchedulerService,
this.taskSchedulerService, this.logService,
this.logService, lockedCallback,
lockedCallback, logoutCallback,
logoutCallback, );
);
}
this.containerService = new ContainerService(this.keyService, this.encryptService); this.containerService = new ContainerService(this.keyService, this.encryptService);
this.sendStateProvider = new SendStateProvider(this.stateProvider); this.sendStateProvider = new SendStateProvider(this.stateProvider);
@ -913,59 +899,41 @@ export default class MainBackground {
this.providerService = new ProviderService(this.stateProvider); this.providerService = new ProviderService(this.stateProvider);
if (this.popupOnlyContext) { this.syncService = new DefaultSyncService(
this.syncService = new ForegroundSyncService( this.masterPasswordService,
this.stateService, this.accountService,
this.folderService, this.apiService,
this.folderApiService, this.domainSettingsService,
this.messagingService, this.folderService,
this.logService, this.cipherService,
this.cipherService, this.keyService,
this.collectionService, this.collectionService,
this.apiService, this.messagingService,
this.accountService, this.policyService,
this.authService, this.sendService,
this.sendService, this.logService,
this.sendApiService, this.keyConnectorService,
messageListener, this.stateService,
this.stateProvider, this.providerService,
); this.folderApiService,
} else { this.organizationService,
this.syncService = new DefaultSyncService( this.sendApiService,
this.masterPasswordService, this.userDecryptionOptionsService,
this.accountService, this.avatarService,
this.apiService, logoutCallback,
this.domainSettingsService, this.billingAccountProfileStateService,
this.folderService, this.tokenService,
this.cipherService, this.authService,
this.keyService, this.stateProvider,
this.collectionService, );
this.messagingService,
this.policyService, this.syncServiceListener = new SyncServiceListener(
this.sendService, this.syncService,
this.logService, messageListener,
this.keyConnectorService, this.messagingService,
this.stateService, this.logService,
this.providerService, );
this.folderApiService,
this.organizationService,
this.sendApiService,
this.userDecryptionOptionsService,
this.avatarService,
logoutCallback,
this.billingAccountProfileStateService,
this.tokenService,
this.authService,
this.stateProvider,
);
this.syncServiceListener = new SyncServiceListener(
this.syncService,
messageListener,
this.messagingService,
this.logService,
);
}
this.eventUploadService = new EventUploadService( this.eventUploadService = new EventUploadService(
this.apiService, this.apiService,
this.stateProvider, this.stateProvider,
@ -1112,122 +1080,128 @@ export default class MainBackground {
this.isSafari = this.platformUtilsService.isSafari(); this.isSafari = this.platformUtilsService.isSafari();
// Background // Background
if (!this.popupOnlyContext) {
this.fido2Background = new Fido2Background(
this.logService,
this.fido2ActiveRequestManager,
this.fido2ClientService,
this.vaultSettingsService,
this.scriptInjectorService,
this.configService,
this.authService,
);
const lockService = new DefaultLockService(this.accountService, this.vaultTimeoutService); this.fido2Background = new Fido2Background(
this.logService,
this.fido2ActiveRequestManager,
this.fido2ClientService,
this.vaultSettingsService,
this.scriptInjectorService,
this.configService,
this.authService,
);
this.runtimeBackground = new RuntimeBackground( const lockService = new DefaultLockService(this.accountService, this.vaultTimeoutService);
this,
this.autofillService,
this.platformUtilsService as BrowserPlatformUtilsService,
this.notificationsService,
this.autofillSettingsService,
this.processReloadService,
this.environmentService,
this.messagingService,
this.logService,
this.configService,
messageListener,
this.accountService,
lockService,
);
this.nativeMessagingBackground = new NativeMessagingBackground(
this.keyService,
this.encryptService,
this.cryptoFunctionService,
this.runtimeBackground,
this.messagingService,
this.appIdService,
this.platformUtilsService,
this.logService,
this.authService,
this.biometricStateService,
this.accountService,
);
this.commandsBackground = new CommandsBackground(
this,
this.platformUtilsService,
this.vaultTimeoutService,
this.authService,
() => this.generatePasswordToClipboard(),
);
this.notificationBackground = new NotificationBackground(
this.autofillService,
this.cipherService,
this.authService,
this.policyService,
this.folderService,
this.userNotificationSettingsService,
this.domainSettingsService,
this.environmentService,
this.logService,
this.themeStateService,
this.configService,
this.accountService,
);
this.overlayNotificationsBackground = new OverlayNotificationsBackground( this.runtimeBackground = new RuntimeBackground(
this.logService, this,
this.configService, this.autofillService,
this.notificationBackground, this.platformUtilsService as BrowserPlatformUtilsService,
); this.notificationsService,
this.autofillSettingsService,
this.processReloadService,
this.environmentService,
this.messagingService,
this.logService,
this.configService,
messageListener,
this.accountService,
lockService,
);
this.nativeMessagingBackground = new NativeMessagingBackground(
this.keyService,
this.encryptService,
this.cryptoFunctionService,
this.runtimeBackground,
this.messagingService,
this.appIdService,
this.platformUtilsService,
this.logService,
this.authService,
this.biometricStateService,
this.accountService,
);
this.commandsBackground = new CommandsBackground(
this,
this.platformUtilsService,
this.vaultTimeoutService,
this.authService,
() => this.generatePasswordToClipboard(),
);
this.notificationBackground = new NotificationBackground(
this.autofillService,
this.cipherService,
this.authService,
this.policyService,
this.folderService,
this.userNotificationSettingsService,
this.domainSettingsService,
this.environmentService,
this.logService,
this.themeStateService,
this.configService,
this.accountService,
);
this.filelessImporterBackground = new FilelessImporterBackground( this.overlayNotificationsBackground = new OverlayNotificationsBackground(
this.configService, this.logService,
this.authService, this.configService,
this.policyService, this.notificationBackground,
this.notificationBackground, );
this.importService,
this.syncService,
this.scriptInjectorService,
);
this.autoSubmitLoginBackground = new AutoSubmitLoginBackground( this.filelessImporterBackground = new FilelessImporterBackground(
this.logService, this.configService,
this.autofillService, this.authService,
this.scriptInjectorService, this.policyService,
this.authService, this.notificationBackground,
this.configService, this.importService,
this.platformUtilsService, this.syncService,
this.policyService, this.scriptInjectorService,
); );
const contextMenuClickedHandler = new ContextMenuClickedHandler( this.autoSubmitLoginBackground = new AutoSubmitLoginBackground(
(options) => this.platformUtilsService.copyToClipboard(options.text), this.logService,
async () => this.generatePasswordToClipboard(), this.autofillService,
async (tab, cipher) => { this.scriptInjectorService,
this.loginToAutoFill = cipher; this.authService,
if (tab == null) { this.configService,
return; this.platformUtilsService,
} this.policyService,
);
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. const contextMenuClickedHandler = new ContextMenuClickedHandler(
// eslint-disable-next-line @typescript-eslint/no-floating-promises (options) => this.platformUtilsService.copyToClipboard(options.text),
BrowserApi.tabSendMessage(tab, { async (_tab) => {
command: "collectPageDetails", const options = (await this.passwordGenerationService.getOptions())?.[0] ?? {};
tab: tab, const password = await this.passwordGenerationService.generatePassword(options);
sender: "contextMenu", this.platformUtilsService.copyToClipboard(password);
}); // 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.authService, this.passwordGenerationService.addHistory(password);
this.cipherService, },
this.totpService, async (tab, cipher) => {
this.eventCollectionService, this.loginToAutoFill = cipher;
this.userVerificationService, if (tab == null) {
this.accountService, return;
); }
this.contextMenusBackground = new ContextMenusBackground(contextMenuClickedHandler); // 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
BrowserApi.tabSendMessage(tab, {
command: "collectPageDetails",
tab: tab,
sender: "contextMenu",
});
},
this.authService,
this.cipherService,
this.totpService,
this.eventCollectionService,
this.userVerificationService,
this.accountService,
);
this.contextMenusBackground = new ContextMenusBackground(contextMenuClickedHandler);
this.idleBackground = new IdleBackground( this.idleBackground = new IdleBackground(
this.vaultTimeoutService, this.vaultTimeoutService,
@ -1246,29 +1220,27 @@ export default class MainBackground {
this.stateProvider, this.stateProvider,
); );
if (!this.popupOnlyContext) { this.mainContextMenuHandler = new MainContextMenuHandler(
this.mainContextMenuHandler = new MainContextMenuHandler( this.stateService,
this.stateService, this.autofillSettingsService,
this.autofillSettingsService, this.i18nService,
this.i18nService, this.logService,
this.logService, this.billingAccountProfileStateService,
this.billingAccountProfileStateService, );
);
this.cipherContextMenuHandler = new CipherContextMenuHandler( this.cipherContextMenuHandler = new CipherContextMenuHandler(
this.mainContextMenuHandler, this.mainContextMenuHandler,
this.authService, this.authService,
this.cipherService,
);
if (chrome.webRequest != null && chrome.webRequest.onAuthRequired != null) {
this.webRequestBackground = new WebRequestBackground(
this.platformUtilsService,
this.cipherService, this.cipherService,
this.authService,
chrome.webRequest,
); );
if (chrome.webRequest != null && chrome.webRequest.onAuthRequired != null) {
this.webRequestBackground = new WebRequestBackground(
this.platformUtilsService,
this.cipherService,
this.authService,
chrome.webRequest,
);
}
} }
this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.keyService); this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.keyService);
@ -1283,7 +1255,7 @@ export default class MainBackground {
this.containerService.attachToGlobal(self); this.containerService.attachToGlobal(self);
// Only the "true" background should run migrations // Only the "true" background should run migrations
await this.stateService.init({ runMigrations: !this.popupOnlyContext }); await this.stateService.init({ runMigrations: true });
// This is here instead of in in the InitService b/c we don't plan for // This is here instead of in in the InitService b/c we don't plan for
// side effects to run in the Browser InitService. // side effects to run in the Browser InitService.
@ -1305,10 +1277,6 @@ export default class MainBackground {
this.popupViewCacheBackgroundService.startObservingTabChanges(); this.popupViewCacheBackgroundService.startObservingTabChanges();
if (this.popupOnlyContext) {
return;
}
await this.vaultTimeoutService.init(true); await this.vaultTimeoutService.init(true);
this.fido2Background.init(); this.fido2Background.init();
await this.runtimeBackground.init(); await this.runtimeBackground.init();
@ -1637,7 +1605,6 @@ export default class MainBackground {
*/ */
async initOverlayAndTabsBackground() { async initOverlayAndTabsBackground() {
if ( if (
this.popupOnlyContext ||
this.overlayBackground || this.overlayBackground ||
this.tabsBackground || this.tabsBackground ||
(await firstValueFrom(this.authService.activeAccountStatus$)) === (await firstValueFrom(this.authService.activeAccountStatus$)) ===

View File

@ -24,8 +24,8 @@ import {
LockComponentService, LockComponentService,
} from "@bitwarden/auth/angular"; } from "@bitwarden/auth/angular";
import { LockService, LoginEmailService, PinServiceAbstraction } from "@bitwarden/auth/common"; import { LockService, LoginEmailService, PinServiceAbstraction } from "@bitwarden/auth/common";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { EventCollectionService as EventCollectionServiceAbstraction } from "@bitwarden/common/abstractions/event/event-collection.service"; import { EventCollectionService as EventCollectionServiceAbstraction } from "@bitwarden/common/abstractions/event/event-collection.service";
import { NotificationsService } from "@bitwarden/common/abstractions/notifications.service";
import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service"; import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
@ -92,9 +92,15 @@ import { InlineDerivedStateProvider } from "@bitwarden/common/platform/state/imp
import { PrimarySecondaryStorageService } from "@bitwarden/common/platform/storage/primary-secondary-storage.service"; import { PrimarySecondaryStorageService } from "@bitwarden/common/platform/storage/primary-secondary-storage.service";
import { WindowStorageService } from "@bitwarden/common/platform/storage/window-storage.service"; import { WindowStorageService } from "@bitwarden/common/platform/storage/window-storage.service";
import { SyncService } from "@bitwarden/common/platform/sync"; import { SyncService } from "@bitwarden/common/platform/sync";
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
import { InternalSendService } from "@bitwarden/common/tools/send/services/send.service.abstraction";
import { VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.type"; import { VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.type";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { FolderService as FolderServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction";
import {
FolderService as FolderServiceAbstraction,
InternalFolderService,
} from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction";
import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/vault/abstractions/totp.service"; import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/vault/abstractions/totp.service";
import { TotpService } from "@bitwarden/common/vault/services/totp.service"; import { TotpService } from "@bitwarden/common/vault/services/totp.service";
import { DialogService, ToastService } from "@bitwarden/components"; import { DialogService, ToastService } from "@bitwarden/components";
@ -107,7 +113,6 @@ import { ExtensionAnonLayoutWrapperDataService } from "../../auth/popup/extensio
import { ExtensionLoginComponentService } from "../../auth/popup/login/extension-login-component.service"; import { ExtensionLoginComponentService } from "../../auth/popup/login/extension-login-component.service";
import { AutofillService as AutofillServiceAbstraction } from "../../autofill/services/abstractions/autofill.service"; import { AutofillService as AutofillServiceAbstraction } from "../../autofill/services/abstractions/autofill.service";
import AutofillService from "../../autofill/services/autofill.service"; import AutofillService from "../../autofill/services/autofill.service";
import MainBackground from "../../background/main.background";
import { ForegroundBrowserBiometricsService } from "../../key-management/biometrics/foreground-browser-biometrics"; import { ForegroundBrowserBiometricsService } from "../../key-management/biometrics/foreground-browser-biometrics";
import { BrowserKeyService } from "../../key-management/browser-key.service"; import { BrowserKeyService } from "../../key-management/browser-key.service";
import { BrowserApi } from "../../platform/browser/browser-api"; import { BrowserApi } from "../../platform/browser/browser-api";
@ -117,12 +122,12 @@ import { ChromeMessageSender } from "../../platform/messaging/chrome-message.sen
/* eslint-enable no-restricted-imports */ /* eslint-enable no-restricted-imports */
import { OffscreenDocumentService } from "../../platform/offscreen-document/abstractions/offscreen-document"; import { OffscreenDocumentService } from "../../platform/offscreen-document/abstractions/offscreen-document";
import { DefaultOffscreenDocumentService } from "../../platform/offscreen-document/offscreen-document.service"; import { DefaultOffscreenDocumentService } from "../../platform/offscreen-document/offscreen-document.service";
import BrowserPopupUtils from "../../platform/popup/browser-popup-utils";
import { BrowserFileDownloadService } from "../../platform/popup/services/browser-file-download.service"; import { BrowserFileDownloadService } from "../../platform/popup/services/browser-file-download.service";
import { PopupViewCacheService } from "../../platform/popup/view-cache/popup-view-cache.service"; import { PopupViewCacheService } from "../../platform/popup/view-cache/popup-view-cache.service";
import { ScriptInjectorService } from "../../platform/services/abstractions/script-injector.service"; import { ScriptInjectorService } from "../../platform/services/abstractions/script-injector.service";
import { BrowserEnvironmentService } from "../../platform/services/browser-environment.service"; import { BrowserEnvironmentService } from "../../platform/services/browser-environment.service";
import BrowserLocalStorageService from "../../platform/services/browser-local-storage.service"; import BrowserLocalStorageService from "../../platform/services/browser-local-storage.service";
import BrowserMemoryStorageService from "../../platform/services/browser-memory-storage.service";
import { BrowserScriptInjectorService } from "../../platform/services/browser-script-injector.service"; import { BrowserScriptInjectorService } from "../../platform/services/browser-script-injector.service";
import I18nService from "../../platform/services/i18n.service"; import I18nService from "../../platform/services/i18n.service";
import { ForegroundPlatformUtilsService } from "../../platform/services/platform-utils/foreground-platform-utils.service"; import { ForegroundPlatformUtilsService } from "../../platform/services/platform-utils/foreground-platform-utils.service";
@ -130,6 +135,7 @@ import { BrowserSdkClientFactory } from "../../platform/services/sdk/browser-sdk
import { ForegroundTaskSchedulerService } from "../../platform/services/task-scheduler/foreground-task-scheduler.service"; import { ForegroundTaskSchedulerService } from "../../platform/services/task-scheduler/foreground-task-scheduler.service";
import { BrowserStorageServiceProvider } from "../../platform/storage/browser-storage-service.provider"; import { BrowserStorageServiceProvider } from "../../platform/storage/browser-storage-service.provider";
import { ForegroundMemoryStorageService } from "../../platform/storage/foreground-memory-storage.service"; import { ForegroundMemoryStorageService } from "../../platform/storage/foreground-memory-storage.service";
import { ForegroundSyncService } from "../../platform/sync/foreground-sync.service";
import { fromChromeRuntimeMessaging } from "../../platform/utils/from-chrome-runtime-messaging"; import { fromChromeRuntimeMessaging } from "../../platform/utils/from-chrome-runtime-messaging";
import { ExtensionLockComponentService } from "../../services/extension-lock-component.service"; import { ExtensionLockComponentService } from "../../services/extension-lock-component.service";
import { ForegroundVaultTimeoutService } from "../../services/vault-timeout/foreground-vault-timeout.service"; import { ForegroundVaultTimeoutService } from "../../services/vault-timeout/foreground-vault-timeout.service";
@ -151,26 +157,6 @@ const DISK_BACKUP_LOCAL_STORAGE = new SafeInjectionToken<
AbstractStorageService & ObservableStorageService AbstractStorageService & ObservableStorageService
>("DISK_BACKUP_LOCAL_STORAGE"); >("DISK_BACKUP_LOCAL_STORAGE");
const needsBackgroundInit = BrowserPopupUtils.backgroundInitializationRequired();
const mainBackground: MainBackground = needsBackgroundInit
? createLocalBgService()
: BrowserApi.getBackgroundPage().bitwardenMain;
function createLocalBgService() {
const localBgService = new MainBackground(true);
// 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
localBgService.bootstrap();
return localBgService;
}
/** @deprecated This method needs to be removed as part of MV3 conversion. Please do not add more and actively try to remove usages */
function getBgService<T>(service: keyof MainBackground) {
return (): T => {
return mainBackground ? (mainBackground[service] as any as T) : null;
};
}
/** /**
* Provider definitions used in the ngModule. * Provider definitions used in the ngModule.
* Add your provider definition here using the safeProvider function as a wrapper. This will give you type safety. * Add your provider definition here using the safeProvider function as a wrapper. This will give you type safety.
@ -307,8 +293,23 @@ const safeProviders: SafeProvider[] = [
}), }),
safeProvider({ safeProvider({
provide: SyncService, provide: SyncService,
useFactory: getBgService<SyncService>("syncService"), useClass: ForegroundSyncService,
deps: [], deps: [
StateService,
InternalFolderService,
FolderApiServiceAbstraction,
MessageSender,
LogService,
CipherService,
CollectionService,
ApiService,
AccountServiceAbstraction,
AuthService,
InternalSendService,
SendApiService,
MessageListener,
StateProvider,
],
}), }),
safeProvider({ safeProvider({
provide: DomainSettingsService, provide: DomainSettingsService,
@ -358,11 +359,6 @@ const safeProviders: SafeProvider[] = [
useClass: ForegroundVaultTimeoutService, useClass: ForegroundVaultTimeoutService,
deps: [MessagingServiceAbstraction], deps: [MessagingServiceAbstraction],
}), }),
safeProvider({
provide: NotificationsService,
useFactory: getBgService<NotificationsService>("notificationsService"),
deps: [],
}),
safeProvider({ safeProvider({
provide: VaultFilterService, provide: VaultFilterService,
useClass: VaultFilterService, useClass: VaultFilterService,
@ -382,8 +378,8 @@ const safeProviders: SafeProvider[] = [
}), }),
safeProvider({ safeProvider({
provide: MEMORY_STORAGE, provide: MEMORY_STORAGE,
useFactory: getBgService<AbstractStorageService>("memoryStorageService"), useFactory: (memoryStorage: AbstractStorageService) => memoryStorage,
deps: [], deps: [OBSERVABLE_MEMORY_STORAGE],
}), }),
safeProvider({ safeProvider({
provide: OBSERVABLE_MEMORY_STORAGE, provide: OBSERVABLE_MEMORY_STORAGE,
@ -392,9 +388,7 @@ const safeProviders: SafeProvider[] = [
return new ForegroundMemoryStorageService(); return new ForegroundMemoryStorageService();
} }
return getBgService<AbstractStorageService & ObservableStorageService>( return new BrowserMemoryStorageService();
"memoryStorageForStateProviders",
)();
}, },
deps: [], deps: [],
}), }),
@ -407,9 +401,7 @@ const safeProviders: SafeProvider[] = [
return regularMemoryStorageService; return regularMemoryStorageService;
} }
return getBgService<AbstractStorageService & ObservableStorageService>( return new ForegroundMemoryStorageService();
"largeObjectMemoryStorageForStateProviders",
)();
}, },
deps: [OBSERVABLE_MEMORY_STORAGE], deps: [OBSERVABLE_MEMORY_STORAGE],
}), }),
@ -494,15 +486,7 @@ const safeProviders: SafeProvider[] = [
}), }),
safeProvider({ safeProvider({
provide: INTRAPROCESS_MESSAGING_SUBJECT, provide: INTRAPROCESS_MESSAGING_SUBJECT,
useFactory: () => { useFactory: () => new Subject<Message<Record<string, unknown>>>(),
if (BrowserPopupUtils.backgroundInitializationRequired()) {
// There is no persistent main background which means we have one in memory,
// we need the same instance that our in memory background is utilizing.
return getBgService("intraprocessMessagingSubject")();
} else {
return new Subject<Message<Record<string, unknown>>>();
}
},
deps: [], deps: [],
}), }),
safeProvider({ safeProvider({
@ -514,23 +498,6 @@ const safeProviders: SafeProvider[] = [
), ),
deps: [INTRAPROCESS_MESSAGING_SUBJECT, LogService], deps: [INTRAPROCESS_MESSAGING_SUBJECT, LogService],
}), }),
safeProvider({
provide: INTRAPROCESS_MESSAGING_SUBJECT,
useFactory: () => {
if (needsBackgroundInit) {
// We will have created a popup within this context, in that case
// we want to make sure we have the same subject as that context so we
// can message with it.
return getBgService("intraprocessMessagingSubject")();
} else {
// There isn't a locally created background so we will communicate with
// the true background through chrome apis, in that case, we can just create
// one for ourself.
return new Subject<Message<Record<string, unknown>>>();
}
},
deps: [],
}),
safeProvider({ safeProvider({
provide: DISK_BACKUP_LOCAL_STORAGE, provide: DISK_BACKUP_LOCAL_STORAGE,
useFactory: (diskStorage: AbstractStorageService & ObservableStorageService) => useFactory: (diskStorage: AbstractStorageService & ObservableStorageService) =>
@ -572,13 +539,7 @@ const safeProviders: SafeProvider[] = [
}), }),
safeProvider({ safeProvider({
provide: ForegroundTaskSchedulerService, provide: ForegroundTaskSchedulerService,
useFactory: (logService: LogService, stateProvider: StateProvider) => { useClass: ForegroundTaskSchedulerService,
if (needsBackgroundInit) {
return getBgService<ForegroundTaskSchedulerService>("taskSchedulerService")();
}
return new ForegroundTaskSchedulerService(logService, stateProvider);
},
deps: [LogService, StateProvider], deps: [LogService, StateProvider],
}), }),
safeProvider({ safeProvider({