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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

252 lines
8.4 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";
[SG-998] and [SG-999] Vault and Autofill team refactor (#4542) * Move DeprecatedVaultFilterService to vault folder * [libs] move VaultItemsComponent * [libs] move AddEditComponent * [libs] move AddEditCustomFields * [libs] move attachmentsComponent * [libs] folderAddEditComponent * [libs] IconComponent * [libs] PasswordRepormptComponent * [libs] PremiumComponent * [libs] ViewCustomFieldsComponent * [libs] ViewComponent * [libs] PasswordRepromptService * [libs] Move FolderService and FolderApiService abstractions * [libs] FolderService imports * [libs] PasswordHistoryComponent * [libs] move Sync and SyncNotifier abstractions * [libs] SyncService imports * [libs] fix file casing for passwordReprompt abstraction * [libs] SyncNotifier import fix * [libs] CipherServiceAbstraction * [libs] PasswordRepromptService abstraction * [libs] Fix file casing for angular passwordReprompt service * [libs] fix file casing for SyncNotifierService * [libs] CipherRepromptType * [libs] rename CipherRepromptType * [libs] CipherType * [libs] Rename CipherType * [libs] CipherData * [libs] FolderData * [libs] PasswordHistoryData * [libs] AttachmentData * [libs] CardData * [libs] FieldData * [libs] IdentityData * [libs] LocalData * [libs] LoginData * [libs] SecureNoteData * [libs] LoginUriData * [libs] Domain classes * [libs] SecureNote * [libs] Request models * [libs] Response models * [libs] View part 1 * [libs] Views part 2 * [libs] Move folder services * [libs] Views fixes * [libs] Move sync services * [libs] cipher service * [libs] Types * [libs] Sync file casing * [libs] Fix folder service import * [libs] Move spec files * [libs] casing fixes on spec files * [browser] Autofill background, clipboard, commands * [browser] Fix ContextMenusBackground casing * [browser] Rename fix * [browser] Autofill content * [browser] autofill.js * [libs] enpass importer spec fix * [browser] autofill models * [browser] autofill manifest path updates * [browser] Autofill notification files * [browser] autofill services * [browser] Fix file casing * [browser] Vault popup loose components * [browser] Vault components * [browser] Manifest fixes * [browser] Vault services * [cli] vault commands and models * [browser] File capitilization fixes * [desktop] Vault components and services * [web] vault loose components * [web] Vault components * [browser] Fix misc-utils import * [libs] Fix psono spec imports * [fix] Add comments to address lint rules
2023-01-31 22:08:37 +01:00
import { AutofillService } from "../autofill/services/abstractions/autofill.service";
2022-02-24 18:14:04 +01:00
import { BrowserApi } from "../browser/browserApi";
import { BrowserEnvironmentService } from "../services/browser-environment.service";
2021-02-10 16:40:15 +01:00
import BrowserPlatformUtilsService from "../services/browserPlatformUtils.service";
2017-12-07 21:36:24 +01:00
import MainBackground from "./main.background";
import LockedVaultPendingNotificationsItem from "./models/lockedVaultPendingNotificationsItem";
export default class RuntimeBackground {
2018-04-06 17:48:45 +02:00
private autofillTimeout: any;
2017-12-07 21:36:24 +01:00
private pageDetailsToAutoFill: any[] = [];
private onInstalledReason: string = null;
private lockedVaultPendingNotifications: LockedVaultPendingNotificationsItem[] = [];
2021-12-21 15:43:35 +01:00
2017-12-07 21:36:24 +01:00
constructor(
private main: MainBackground,
private autofillService: AutofillService,
private platformUtilsService: BrowserPlatformUtilsService,
2018-08-20 23:40:39 +02:00
private i18nService: I18nService,
private notificationsService: NotificationsService,
private systemService: SystemService,
private environmentService: BrowserEnvironmentService,
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;
});
2021-12-21 15:43:35 +01:00
}
async init() {
if (!chrome.runtime) {
2021-12-21 15:43:35 +01:00
return;
}
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);
Ps 1291 fix extension icon updates (#3571) * Add needed factories for AuthService WIP: Allow console logs * Add badge updates * Init by listener * Improve tab identification * Define MV3 background init * Init services in factories. Requires conversion of all factories to promises. We need to initialize in factory since the requester of a service doesn't necessarily know all dependencies for that service. The only alternative is to create an out parameter for a generated init function, which isn't ideal. * Improve badge setting * Use `update-badge` in mv2 and mv3 Separates menu and badge updates * Use update-badge everywhere * Use BrowserApi where possible * Update factories * Merge duplicated methods * Continue using private mode messager for now * Add static platform determination. * Break down methods and extract BrowserApi Concerns * Prefer strict equals * Init two-factor service in factory * Use globalThis types * Prefer `globalThis` * Use Window type definition updated with Opera Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> * Distinguish Opera from Safari Opera includes Gecko, Chrome, Safari, and Opera in its user agent. We need to make sure that we're not in Opera prior to testing Safari. * Update import * Initialize search-service for update badge context * Build all browser MV3 artifacts only uploading Chrome, Edge and Opera artifacts for now, as those support manifest V3 Also corrects build artifact to lower case. * Remove individual dist Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2022-10-19 15:55:57 +02:00
if (this.main.popupOnlyContext) {
(window as any).bitwardenBackgroundMessageListener = backgroundMessageListener;
}
2021-12-21 15:43:35 +01:00
}
async processMessage(msg: any, sender: chrome.runtime.MessageSender, sendResponse: any) {
2018-01-12 21:20:19 +01:00
switch (msg.command) {
case "loggedIn":
2022-02-24 18:14:04 +01:00
case "unlocked": {
let item: LockedVaultPendingNotificationsItem;
2021-12-21 15:43:35 +01:00
if (this.lockedVaultPendingNotifications?.length > 0) {
item = this.lockedVaultPendingNotifications.pop();
BrowserApi.closeBitwardenExtensionTab();
2017-12-07 21:36:24 +01:00
}
Ps 1291 fix extension icon updates (#3571) * Add needed factories for AuthService WIP: Allow console logs * Add badge updates * Init by listener * Improve tab identification * Define MV3 background init * Init services in factories. Requires conversion of all factories to promises. We need to initialize in factory since the requester of a service doesn't necessarily know all dependencies for that service. The only alternative is to create an out parameter for a generated init function, which isn't ideal. * Improve badge setting * Use `update-badge` in mv2 and mv3 Separates menu and badge updates * Use update-badge everywhere * Use BrowserApi where possible * Update factories * Merge duplicated methods * Continue using private mode messager for now * Add static platform determination. * Break down methods and extract BrowserApi Concerns * Prefer strict equals * Init two-factor service in factory * Use globalThis types * Prefer `globalThis` * Use Window type definition updated with Opera Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> * Distinguish Opera from Safari Opera includes Gecko, Chrome, Safari, and Opera in its user agent. We need to make sure that we're not in Opera prior to testing Safari. * Update import * Initialize search-service for update badge context * Build all browser MV3 artifacts only uploading Chrome, Edge and Opera artifacts for now, as those support manifest V3 Also corrects build artifact to lower case. * Remove individual dist Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2022-10-19 15:55:57 +02:00
await this.main.refreshBadge();
await this.main.refreshMenu(false);
2021-10-18 16:34:14 +02:00
this.notificationsService.updateConnection(msg.command === "unlocked");
this.systemService.cancelProcessReload();
2021-12-21 15:43:35 +01:00
2021-10-18 16:34:14 +02:00
if (item) {
await BrowserApi.tabSendMessageData(
item.commandToRetry.sender.tab,
"unlockCompleted",
2021-12-21 15:43:35 +01:00
item
);
}
break;
2022-02-24 18:14:04 +01:00
}
2021-10-18 16:34:14 +02:00
case "addToLockedVaultPendingNotifications":
this.lockedVaultPendingNotifications.push(msg.data);
2021-12-21 15:43:35 +01:00
break;
2021-10-18 16:34:14 +02:00
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;
2021-10-18 16:34:14 +02:00
case "syncCompleted":
if (msg.successfully) {
Ps 1291 fix extension icon updates (#3571) * Add needed factories for AuthService WIP: Allow console logs * Add badge updates * Init by listener * Improve tab identification * Define MV3 background init * Init services in factories. Requires conversion of all factories to promises. We need to initialize in factory since the requester of a service doesn't necessarily know all dependencies for that service. The only alternative is to create an out parameter for a generated init function, which isn't ideal. * Improve badge setting * Use `update-badge` in mv2 and mv3 Separates menu and badge updates * Use update-badge everywhere * Use BrowserApi where possible * Update factories * Merge duplicated methods * Continue using private mode messager for now * Add static platform determination. * Break down methods and extract BrowserApi Concerns * Prefer strict equals * Init two-factor service in factory * Use globalThis types * Prefer `globalThis` * Use Window type definition updated with Opera Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> * Distinguish Opera from Safari Opera includes Gecko, Chrome, Safari, and Opera in its user agent. We need to make sure that we're not in Opera prior to testing Safari. * Update import * Initialize search-service for update badge context * Build all browser MV3 artifacts only uploading Chrome, Edge and Opera artifacts for now, as those support manifest V3 Also corrects build artifact to lower case. * Remove individual dist Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2022-10-19 15:55:57 +02:00
setTimeout(async () => {
await this.main.refreshBadge();
await this.main.refreshMenu();
}, 2000);
this.main.avatarUpdateService.loadColorFromState();
2021-12-21 15:43:35 +01:00
}
break;
2018-01-18 22:17:58 +01:00
case "openPopup":
await this.main.openPopup();
2021-12-21 15:43:35 +01:00
break;
case "promptForLogin":
BrowserApi.openBitwardenExtensionTab("popup/index.html", true, sender.tab);
break;
case "openAddEditCipher": {
const addEditCipherUrl =
msg.data?.cipherId == null
? "popup/index.html#/edit-cipher"
: "popup/index.html#/edit-cipher?cipherId=" + msg.data.cipherId;
BrowserApi.openBitwardenExtensionTab(addEditCipherUrl, true, sender.tab);
break;
}
case "closeTab":
setTimeout(() => {
BrowserApi.closeBitwardenExtensionTab();
}, msg.delay ?? 0);
2021-12-21 15:43:35 +01:00
break;
2021-10-18 16:34:14 +02:00
case "showDialogResolve":
2018-01-12 21:20:19 +01:00
this.platformUtilsService.resolveDialogPromise(msg.dialogId, msg.confirmed);
2021-12-21 15:43:35 +01:00
break;
2018-01-12 21:20:19 +01:00
case "bgCollectPageDetails":
await this.main.collectPageDetailsForContentScript(sender.tab, msg.sender, sender.frameId);
2021-12-21 15:43:35 +01:00
break;
2018-01-12 21:20:19 +01:00
case "bgUpdateContextMenu":
case "editedCipher":
case "addedCipher":
case "deletedCipher":
Ps 1291 fix extension icon updates (#3571) * Add needed factories for AuthService WIP: Allow console logs * Add badge updates * Init by listener * Improve tab identification * Define MV3 background init * Init services in factories. Requires conversion of all factories to promises. We need to initialize in factory since the requester of a service doesn't necessarily know all dependencies for that service. The only alternative is to create an out parameter for a generated init function, which isn't ideal. * Improve badge setting * Use `update-badge` in mv2 and mv3 Separates menu and badge updates * Use update-badge everywhere * Use BrowserApi where possible * Update factories * Merge duplicated methods * Continue using private mode messager for now * Add static platform determination. * Break down methods and extract BrowserApi Concerns * Prefer strict equals * Init two-factor service in factory * Use globalThis types * Prefer `globalThis` * Use Window type definition updated with Opera Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> * Distinguish Opera from Safari Opera includes Gecko, Chrome, Safari, and Opera in its user agent. We need to make sure that we're not in Opera prior to testing Safari. * Update import * Initialize search-service for update badge context * Build all browser MV3 artifacts only uploading Chrome, Edge and Opera artifacts for now, as those support manifest V3 Also corrects build artifact to lower case. * Remove individual dist Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2022-10-19 15:55:57 +02:00
await this.main.refreshBadge();
await this.main.refreshMenu();
2021-12-21 15:43:35 +01:00
break;
case "bgReseedStorage":
2019-02-13 17:34:42 +01:00
await this.main.reseedStorage();
2021-12-21 15:43:35 +01:00
break;
2018-01-12 21:20:19 +01:00
case "collectPageDetailsResponse":
switch (msg.sender) {
case "autofiller":
2022-02-24 18:14:04 +01:00
case "autofill_cmd": {
const totpCode = await this.autofillService.doAutoFillActiveTab(
2021-12-21 15:43:35 +01:00
[
{
2018-01-12 21:20:19 +01:00
frameId: sender.frameId,
tab: msg.tab,
details: msg.details,
2021-12-21 15:43:35 +01:00
},
],
2018-01-12 21:20:19 +01:00
msg.sender === "autofill_cmd"
2021-12-21 15:43:35 +01:00
);
2018-08-31 03:47:49 +02:00
if (totpCode != null) {
2018-01-12 21:20:19 +01:00
this.platformUtilsService.copyToClipboard(totpCode, { window: window });
2021-12-21 15:43:35 +01:00
}
break;
2022-02-24 18:14:04 +01:00
}
2018-01-12 21:20:19 +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;
}
2021-12-21 15:43:35 +01:00
break;
2022-02-24 18:14:04 +01:00
case "authResult": {
const vaultUrl = this.environmentService.getWebVaultUrl();
2017-12-07 21:36:24 +01:00
2018-01-12 21:20:19 +01:00
if (msg.referrer == null || Utils.getHostname(vaultUrl) !== msg.referrer) {
return;
2018-01-12 21:20:19 +01:00
}
2017-12-07 21:36:24 +01:00
try {
BrowserApi.createNewTab(
"popup/index.html?uilocation=popout#/sso?code=" +
encodeURIComponent(msg.code) +
2021-12-21 15:43:35 +01:00
"&state=" +
encodeURIComponent(msg.state)
2021-12-21 15:43:35 +01:00
);
} catch {
this.logService.error("Unable to open sso popout tab");
2021-12-21 15:43:35 +01:00
}
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) {
return;
}
2017-12-07 21:36:24 +01:00
const params =
`webAuthnResponse=${encodeURIComponent(msg.data)};` +
`remember=${encodeURIComponent(msg.remember)}`;
BrowserApi.openBitwardenExtensionTab(`popup/index.html#/2fa;${params}`, false);
2021-12-21 15:43:35 +01:00
break;
2022-02-24 18:14:04 +01:00
}
case "reloadPopup":
2017-12-07 21:36:24 +01:00
this.messagingService.send("reloadPopup");
2021-12-21 15:43:35 +01:00
break;
2021-05-12 05:35:18 +02:00
case "emailVerificationRequired":
this.messagingService.send("showDialog", {
2017-12-07 21:36:24 +01:00
dialogId: "emailVerificationRequired",
title: this.i18nService.t("emailVerificationRequired"),
2021-05-12 05:35:18 +02:00
text: this.i18nService.t("emailVerificationRequiredDesc"),
confirmText: this.i18nService.t("ok"),
type: "info",
2021-12-21 15:43:35 +01:00
});
break;
2017-12-07 21:36:24 +01:00
case "getClickedElementResponse":
this.platformUtilsService.copyToClipboard(msg.identifier, { window: window });
2022-02-24 18:14:04 +01:00
break;
2017-12-07 21:36:24 +01:00
default:
2021-12-21 15:43:35 +01:00
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) {
2018-01-18 04:42:31 +01:00
const totpCode = await this.autofillService.doAutoFill({
tab: tabToAutoFill,
2018-01-18 04:42:31 +01:00
cipher: this.main.loginToAutoFill,
pageDetails: this.pageDetailsToAutoFill,
2021-02-10 16:40:15 +01:00
fillNewPassword: true,
2018-01-18 04:42:31 +01:00
});
if (totpCode != null) {
this.platformUtilsService.copyToClipboard(totpCode, { window: window });
2018-01-19 17:42:35 +01:00
}
2018-01-18 04:42:31 +01:00
// reset
this.main.loginToAutoFill = null;
this.pageDetailsToAutoFill = [];
2021-12-21 15:43:35 +01:00
}
2018-01-18 04:42:31 +01:00
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();
}
}
this.onInstalledReason = null;
2021-12-21 15:43:35 +01:00
}
}, 100);
}
}