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

241 lines
8.0 KiB
TypeScript
Raw Normal View History

2022-06-14 17:10:53 +02:00
import { I18nService } from "@bitwarden/common/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/abstractions/log.service";
import { MessagingService } from "@bitwarden/common/abstractions/messaging.service";
import { NotificationsService } from "@bitwarden/common/abstractions/notifications.service";
import { SystemService } from "@bitwarden/common/abstractions/system.service";
import { Utils } from "@bitwarden/common/misc/utils";
2022-02-24 18:14:04 +01:00
import { BrowserApi } from "../browser/browserApi";
2021-12-21 15:43:35 +01:00
import { AutofillService } from "../services/abstractions/autofill.service";
import { BrowserEnvironmentService } from "../services/browser-environment.service";
2021-12-21 15:43:35 +01:00
import BrowserPlatformUtilsService from "../services/browserPlatformUtils.service";
2017-12-07 21:36:24 +01:00
2021-12-21 15:43:35 +01:00
import MainBackground from "./main.background";
import LockedVaultPendingNotificationsItem from "./models/lockedVaultPendingNotificationsItem";
export default class RuntimeBackground {
2021-12-21 15:43:35 +01:00
private autofillTimeout: any;
private pageDetailsToAutoFill: any[] = [];
private onInstalledReason: string = null;
private lockedVaultPendingNotifications: LockedVaultPendingNotificationsItem[] = [];
constructor(
private main: MainBackground,
private autofillService: AutofillService,
private platformUtilsService: BrowserPlatformUtilsService,
private i18nService: I18nService,
private notificationsService: NotificationsService,
private systemService: SystemService,
private environmentService: BrowserEnvironmentService,
2021-12-21 15:43:35 +01:00
private messagingService: MessagingService,
private logService: LogService
) {
// onInstalled listener must be wired up before anything else, so we do it in the ctor
chrome.runtime.onInstalled.addListener((details: any) => {
this.onInstalledReason = details.reason;
});
}
async init() {
if (!chrome.runtime) {
return;
}
2021-12-21 15:43:35 +01:00
await this.checkOnInstalled();
const backgroundMessageListener = async (
msg: any,
sender: chrome.runtime.MessageSender,
sendResponse: any
) => {
await this.processMessage(msg, sender, sendResponse);
};
BrowserApi.messageListener("runtime.background", backgroundMessageListener);
if (this.main.isPrivateMode) {
(window as any).bitwardenBackgroundMessageListener = backgroundMessageListener;
}
2021-12-21 15:43:35 +01:00
}
async processMessage(msg: any, sender: any, sendResponse: any) {
switch (msg.command) {
case "loggedIn":
2022-02-24 18:14:04 +01:00
case "unlocked": {
2021-12-21 15:43:35 +01:00
let item: LockedVaultPendingNotificationsItem;
if (this.lockedVaultPendingNotifications?.length > 0) {
2021-12-21 15:43:35 +01:00
await BrowserApi.closeLoginTab();
item = this.lockedVaultPendingNotifications.pop();
if (item.commandToRetry.sender?.tab?.id) {
await BrowserApi.focusSpecifiedTab(item.commandToRetry.sender.tab.id);
}
2017-12-07 21:36:24 +01:00
}
2021-12-21 15:43:35 +01:00
await this.main.setIcon();
await this.main.refreshBadgeAndMenu(false);
this.notificationsService.updateConnection(msg.command === "unlocked");
this.systemService.cancelProcessReload();
if (item) {
await BrowserApi.tabSendMessageData(
item.commandToRetry.sender.tab,
"unlockCompleted",
item
);
}
break;
2022-02-24 18:14:04 +01:00
}
2021-12-21 15:43:35 +01:00
case "addToLockedVaultPendingNotifications":
this.lockedVaultPendingNotifications.push(msg.data);
break;
case "logout":
[Account Switching] Base changes for account switching (#2250) * Pull in jslib * Create new state models * Create browser specific stateService * Remove registration deprecated services, register stateService * Replace usage of deprecated services (user, constants) * Add missing properties to BrowserGroupingsComponentState * Remove StorageService from initFactory * Clear the correct state * Add null check when restoring send-grouping state * add remember email * Initialize stateservice in services.module * Fix 'lock now' not working * Comment to remove setting defaults on install * Pull jslib * Remove setting defaults on install * Bump jslib * Pass the current userId to services when logging out * Bump jslib * Override vaultTimeout default on account addition * Pull latest jslib * Retrieve vaultTimeout from stateService * Record activity per Account * Add userId to logout and add fallback if not present * Register AccountFactory * Pass userId in messages * Base changes for account switching di fixes (#2280) * [bug] Null checks on Account init * [bug] Use same stateService instance for all operations We override the stateService in browser, but currently don't pull the background service into popup and allow jslib to create its own instance of the base StateService for jslib services. This causes a split in in memory state between the three isntances that results in many errors, namely locking not working. * [chore] Update jslib * Pull in jslib * Pull in jslib * Pull in latest jslib to multiple stateservice inits * Check vault states before executing processReload * Adjust iterator * Update native messaging to include the userId (#2290) * Re-Add UserVerificationService * Fix email not being remembered by base component * Improve readability of reloadProcess * Removed unneeded null check * Fix constructor dependency (stateService) * Added missing await * Simplify dependency registration * Fixed typos * Reverted back to simple loop * Use vaultTimeoutService to retrieve Timeout Co-authored-by: Addison Beck <abeck@bitwarden.com> Co-authored-by: Oscar Hinton <oscar@oscarhinton.com>
2022-01-27 22:22:51 +01:00
await this.main.logout(msg.expired, msg.userId);
2021-12-21 15:43:35 +01:00
break;
case "syncCompleted":
if (msg.successfully) {
setTimeout(async () => await this.main.refreshBadgeAndMenu(), 2000);
}
break;
case "openPopup":
await this.main.openPopup();
break;
case "promptForLogin":
await BrowserApi.createNewTab("popup/index.html?uilocation=popout", true, true);
break;
case "showDialogResolve":
this.platformUtilsService.resolveDialogPromise(msg.dialogId, msg.confirmed);
break;
case "bgCollectPageDetails":
await this.main.collectPageDetailsForContentScript(sender.tab, msg.sender, sender.frameId);
break;
case "bgUpdateContextMenu":
case "editedCipher":
case "addedCipher":
case "deletedCipher":
await this.main.refreshBadgeAndMenu();
break;
case "bgReseedStorage":
await this.main.reseedStorage();
break;
case "collectPageDetailsResponse":
switch (msg.sender) {
case "autofiller":
2022-02-24 18:14:04 +01:00
case "autofill_cmd": {
2021-12-21 15:43:35 +01:00
const totpCode = await this.autofillService.doAutoFillActiveTab(
[
{
frameId: sender.frameId,
tab: msg.tab,
details: msg.details,
},
],
msg.sender === "autofill_cmd"
);
if (totpCode != null) {
this.platformUtilsService.copyToClipboard(totpCode, { window: window });
}
break;
2022-02-24 18:14:04 +01:00
}
2021-12-21 15:43:35 +01:00
case "contextMenu":
clearTimeout(this.autofillTimeout);
this.pageDetailsToAutoFill.push({
frameId: sender.frameId,
tab: msg.tab,
details: msg.details,
});
this.autofillTimeout = setTimeout(async () => await this.autofillPage(msg.tab), 300);
2021-12-21 15:43:35 +01:00
break;
default:
break;
}
break;
2022-02-24 18:14:04 +01:00
case "authResult": {
2021-12-21 15:43:35 +01:00
const vaultUrl = this.environmentService.getWebVaultUrl();
2017-12-07 21:36:24 +01:00
2021-12-21 15:43:35 +01:00
if (msg.referrer == null || Utils.getHostname(vaultUrl) !== msg.referrer) {
return;
2018-01-12 21:20:19 +01:00
}
2021-12-21 15:43:35 +01:00
try {
BrowserApi.createNewTab(
"popup/index.html?uilocation=popout#/sso?code=" +
encodeURIComponent(msg.code) +
"&state=" +
encodeURIComponent(msg.state)
);
} catch {
this.logService.error("Unable to open sso popout tab");
}
break;
2022-02-24 18:14:04 +01:00
}
case "webAuthnResult": {
const vaultUrl = this.environmentService.getWebVaultUrl();
2017-12-07 21:36:24 +01:00
2022-02-24 18:14:04 +01:00
if (msg.referrer == null || Utils.getHostname(vaultUrl) !== msg.referrer) {
2021-12-21 15:43:35 +01:00
return;
}
2021-12-21 15:43:35 +01:00
const params =
`webAuthnResponse=${encodeURIComponent(msg.data)};` +
`remember=${encodeURIComponent(msg.remember)}`;
BrowserApi.createNewTab(
`popup/index.html?uilocation=popout#/2fa;${params}`,
undefined,
false
);
break;
2022-02-24 18:14:04 +01:00
}
2021-12-21 15:43:35 +01:00
case "reloadPopup":
this.messagingService.send("reloadPopup");
break;
case "emailVerificationRequired":
this.messagingService.send("showDialog", {
dialogId: "emailVerificationRequired",
title: this.i18nService.t("emailVerificationRequired"),
text: this.i18nService.t("emailVerificationRequiredDesc"),
confirmText: this.i18nService.t("ok"),
type: "info",
});
break;
case "getClickedElementResponse":
this.platformUtilsService.copyToClipboard(msg.identifier, { window: window });
2022-02-24 18:14:04 +01:00
break;
2021-12-21 15:43:35 +01:00
default:
break;
2017-12-07 21:36:24 +01:00
}
2021-12-21 15:43:35 +01:00
}
2017-12-07 21:36:24 +01:00
private async autofillPage(tabToAutoFill: chrome.tabs.Tab) {
2021-12-21 15:43:35 +01:00
const totpCode = await this.autofillService.doAutoFill({
tab: tabToAutoFill,
2021-12-21 15:43:35 +01:00
cipher: this.main.loginToAutoFill,
pageDetails: this.pageDetailsToAutoFill,
fillNewPassword: true,
});
2021-12-21 15:43:35 +01:00
if (totpCode != null) {
this.platformUtilsService.copyToClipboard(totpCode, { window: window });
2018-01-19 17:42:35 +01:00
}
2021-12-21 15:43:35 +01:00
// reset
this.main.loginToAutoFill = null;
this.pageDetailsToAutoFill = [];
}
private async checkOnInstalled() {
setTimeout(async () => {
if (this.onInstalledReason != null) {
if (this.onInstalledReason === "install") {
BrowserApi.createNewTab("https://bitwarden.com/browser-start/");
if (await this.environmentService.hasManagedEnvironment()) {
await this.environmentService.setUrlsToManagedEnvironment();
}
}
2021-12-21 15:43:35 +01:00
this.onInstalledReason = null;
}
}, 100);
}
}