Run prettier

This commit is contained in:
Robyn MacCallum 2021-12-21 14:48:22 -05:00
parent 40cbf61ab7
commit 42bb8cd5f8
40 changed files with 5928 additions and 5299 deletions

View File

@ -1,16 +1,19 @@
import { NotificationsService } from 'jslib-common/abstractions/notifications.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { StateService } from '../services/abstractions/state.service';
import { NotificationsService } from "jslib-common/abstractions/notifications.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { StateService } from "../services/abstractions/state.service";
const IdleInterval = 60 * 5; // 5 minutes
export default class IdleBackground {
private idle: any;
private idleTimer: number = null;
private idleState = 'active';
private idleState = "active";
constructor(private vaultTimeoutService: VaultTimeoutService, private stateService: StateService,
private notificationsService: NotificationsService) {
constructor(
private vaultTimeoutService: VaultTimeoutService,
private stateService: StateService,
private notificationsService: NotificationsService
) {
this.idle = chrome.idle || (browser != null ? browser.idle : null);
}
@ -20,7 +23,7 @@ export default class IdleBackground {
}
const idleHandler = (newState: string) => {
if (newState === 'active') {
if (newState === "active") {
this.notificationsService.reconnectFromActivity();
} else {
this.notificationsService.disconnectFromInactivity();
@ -35,11 +38,13 @@ export default class IdleBackground {
if (this.idle.onStateChanged) {
this.idle.onStateChanged.addListener(async (newState: string) => {
if (newState === 'locked') { // If the screen is locked or the screensaver activates
if (newState === "locked") {
// If the screen is locked or the screensaver activates
const timeout = await this.stateService.getVaultTimeout();
if (timeout === -2) { // On System Lock vault timeout option
if (timeout === -2) {
// On System Lock vault timeout option
const action = await this.stateService.getVaultTimeoutAction();
if (action === 'logOut') {
if (action === "logOut") {
await this.vaultTimeoutService.logOut();
} else {
await this.vaultTimeoutService.lock(true);

View File

@ -1,96 +1,96 @@
import { CipherRepromptType } from 'jslib-common/enums/cipherRepromptType';
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherRepromptType } from "jslib-common/enums/cipherRepromptType";
import { CipherType } from "jslib-common/enums/cipherType";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CipherView } from "jslib-common/models/view/cipherView";
import { ApiService } from 'jslib-common/services/api.service';
import { AppIdService } from 'jslib-common/services/appId.service';
import { AuditService } from 'jslib-common/services/audit.service';
import { AuthService } from 'jslib-common/services/auth.service';
import { CipherService } from 'jslib-common/services/cipher.service';
import { CollectionService } from 'jslib-common/services/collection.service';
import { ConsoleLogService } from 'jslib-common/services/consoleLog.service';
import { ContainerService } from 'jslib-common/services/container.service';
import { EnvironmentService } from 'jslib-common/services/environment.service';
import { EventService } from 'jslib-common/services/event.service';
import { ExportService } from 'jslib-common/services/export.service';
import { FileUploadService } from 'jslib-common/services/fileUpload.service';
import { FolderService } from 'jslib-common/services/folder.service';
import { KeyConnectorService } from 'jslib-common/services/keyConnector.service';
import { NotificationsService } from 'jslib-common/services/notifications.service';
import { OrganizationService } from 'jslib-common/services/organization.service';
import { PasswordGenerationService } from 'jslib-common/services/passwordGeneration.service';
import { PolicyService } from 'jslib-common/services/policy.service';
import { ProviderService } from 'jslib-common/services/provider.service';
import { SearchService } from 'jslib-common/services/search.service';
import { SendService } from 'jslib-common/services/send.service';
import { SettingsService } from 'jslib-common/services/settings.service';
import { StateMigrationService } from 'jslib-common/services/stateMigration.service';
import { SyncService } from 'jslib-common/services/sync.service';
import { SystemService } from 'jslib-common/services/system.service';
import { TokenService } from 'jslib-common/services/token.service';
import { TotpService } from 'jslib-common/services/totp.service';
import { WebCryptoFunctionService } from 'jslib-common/services/webCryptoFunction.service';
import { ApiService } from "jslib-common/services/api.service";
import { AppIdService } from "jslib-common/services/appId.service";
import { AuditService } from "jslib-common/services/audit.service";
import { AuthService } from "jslib-common/services/auth.service";
import { CipherService } from "jslib-common/services/cipher.service";
import { CollectionService } from "jslib-common/services/collection.service";
import { ConsoleLogService } from "jslib-common/services/consoleLog.service";
import { ContainerService } from "jslib-common/services/container.service";
import { EnvironmentService } from "jslib-common/services/environment.service";
import { EventService } from "jslib-common/services/event.service";
import { ExportService } from "jslib-common/services/export.service";
import { FileUploadService } from "jslib-common/services/fileUpload.service";
import { FolderService } from "jslib-common/services/folder.service";
import { KeyConnectorService } from "jslib-common/services/keyConnector.service";
import { NotificationsService } from "jslib-common/services/notifications.service";
import { OrganizationService } from "jslib-common/services/organization.service";
import { PasswordGenerationService } from "jslib-common/services/passwordGeneration.service";
import { PolicyService } from "jslib-common/services/policy.service";
import { ProviderService } from "jslib-common/services/provider.service";
import { SearchService } from "jslib-common/services/search.service";
import { SendService } from "jslib-common/services/send.service";
import { SettingsService } from "jslib-common/services/settings.service";
import { StateMigrationService } from "jslib-common/services/stateMigration.service";
import { SyncService } from "jslib-common/services/sync.service";
import { SystemService } from "jslib-common/services/system.service";
import { TokenService } from "jslib-common/services/token.service";
import { TotpService } from "jslib-common/services/totp.service";
import { WebCryptoFunctionService } from "jslib-common/services/webCryptoFunction.service";
import { ApiService as ApiServiceAbstraction } from 'jslib-common/abstractions/api.service';
import { AppIdService as AppIdServiceAbstraction } from 'jslib-common/abstractions/appId.service';
import { AuditService as AuditServiceAbstraction } from 'jslib-common/abstractions/audit.service';
import { AuthService as AuthServiceAbstraction } from 'jslib-common/abstractions/auth.service';
import { CipherService as CipherServiceAbstraction } from 'jslib-common/abstractions/cipher.service';
import { CollectionService as CollectionServiceAbstraction } from 'jslib-common/abstractions/collection.service';
import { CryptoService as CryptoServiceAbstraction } from 'jslib-common/abstractions/crypto.service';
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from 'jslib-common/abstractions/cryptoFunction.service';
import { EnvironmentService as EnvironmentServiceAbstraction } from 'jslib-common/abstractions/environment.service';
import { EventService as EventServiceAbstraction } from 'jslib-common/abstractions/event.service';
import { ExportService as ExportServiceAbstraction } from 'jslib-common/abstractions/export.service';
import { FileUploadService as FileUploadServiceAbstraction } from 'jslib-common/abstractions/fileUpload.service';
import { FolderService as FolderServiceAbstraction } from 'jslib-common/abstractions/folder.service';
import { I18nService as I18nServiceAbstraction } from 'jslib-common/abstractions/i18n.service';
import { KeyConnectorService as KeyConnectorServiceAbstraction } from 'jslib-common/abstractions/keyConnector.service';
import { LogService as LogServiceAbstraction } from 'jslib-common/abstractions/log.service';
import { MessagingService as MessagingServiceAbstraction } from 'jslib-common/abstractions/messaging.service';
import { NotificationsService as NotificationsServiceAbstraction } from 'jslib-common/abstractions/notifications.service';
import { OrganizationService as OrganizationServiceAbstraction } from 'jslib-common/abstractions/organization.service';
import { PasswordGenerationService as PasswordGenerationServiceAbstraction } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService as PolicyServiceAbstraction } from 'jslib-common/abstractions/policy.service';
import { ProviderService as ProviderServiceAbstraction } from 'jslib-common/abstractions/provider.service';
import { SearchService as SearchServiceAbstraction } from 'jslib-common/abstractions/search.service';
import { SendService as SendServiceAbstraction } from 'jslib-common/abstractions/send.service';
import { SettingsService as SettingsServiceAbstraction } from 'jslib-common/abstractions/settings.service';
import { StorageService as StorageServiceAbstraction } from 'jslib-common/abstractions/storage.service';
import { SyncService as SyncServiceAbstraction } from 'jslib-common/abstractions/sync.service';
import { SystemService as SystemServiceAbstraction } from 'jslib-common/abstractions/system.service';
import { TokenService as TokenServiceAbstraction } from 'jslib-common/abstractions/token.service';
import { TotpService as TotpServiceAbstraction } from 'jslib-common/abstractions/totp.service';
import { VaultTimeoutService as VaultTimeoutServiceAbstraction } from 'jslib-common/abstractions/vaultTimeout.service';
import { AutofillService as AutofillServiceAbstraction } from '../services/abstractions/autofill.service';
import { ApiService as ApiServiceAbstraction } from "jslib-common/abstractions/api.service";
import { AppIdService as AppIdServiceAbstraction } from "jslib-common/abstractions/appId.service";
import { AuditService as AuditServiceAbstraction } from "jslib-common/abstractions/audit.service";
import { AuthService as AuthServiceAbstraction } from "jslib-common/abstractions/auth.service";
import { CipherService as CipherServiceAbstraction } from "jslib-common/abstractions/cipher.service";
import { CollectionService as CollectionServiceAbstraction } from "jslib-common/abstractions/collection.service";
import { CryptoService as CryptoServiceAbstraction } from "jslib-common/abstractions/crypto.service";
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "jslib-common/abstractions/cryptoFunction.service";
import { EnvironmentService as EnvironmentServiceAbstraction } from "jslib-common/abstractions/environment.service";
import { EventService as EventServiceAbstraction } from "jslib-common/abstractions/event.service";
import { ExportService as ExportServiceAbstraction } from "jslib-common/abstractions/export.service";
import { FileUploadService as FileUploadServiceAbstraction } from "jslib-common/abstractions/fileUpload.service";
import { FolderService as FolderServiceAbstraction } from "jslib-common/abstractions/folder.service";
import { I18nService as I18nServiceAbstraction } from "jslib-common/abstractions/i18n.service";
import { KeyConnectorService as KeyConnectorServiceAbstraction } from "jslib-common/abstractions/keyConnector.service";
import { LogService as LogServiceAbstraction } from "jslib-common/abstractions/log.service";
import { MessagingService as MessagingServiceAbstraction } from "jslib-common/abstractions/messaging.service";
import { NotificationsService as NotificationsServiceAbstraction } from "jslib-common/abstractions/notifications.service";
import { OrganizationService as OrganizationServiceAbstraction } from "jslib-common/abstractions/organization.service";
import { PasswordGenerationService as PasswordGenerationServiceAbstraction } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService as PolicyServiceAbstraction } from "jslib-common/abstractions/policy.service";
import { ProviderService as ProviderServiceAbstraction } from "jslib-common/abstractions/provider.service";
import { SearchService as SearchServiceAbstraction } from "jslib-common/abstractions/search.service";
import { SendService as SendServiceAbstraction } from "jslib-common/abstractions/send.service";
import { SettingsService as SettingsServiceAbstraction } from "jslib-common/abstractions/settings.service";
import { StorageService as StorageServiceAbstraction } from "jslib-common/abstractions/storage.service";
import { SyncService as SyncServiceAbstraction } from "jslib-common/abstractions/sync.service";
import { SystemService as SystemServiceAbstraction } from "jslib-common/abstractions/system.service";
import { TokenService as TokenServiceAbstraction } from "jslib-common/abstractions/token.service";
import { TotpService as TotpServiceAbstraction } from "jslib-common/abstractions/totp.service";
import { VaultTimeoutService as VaultTimeoutServiceAbstraction } from "jslib-common/abstractions/vaultTimeout.service";
import { AutofillService as AutofillServiceAbstraction } from "../services/abstractions/autofill.service";
import { BrowserApi } from '../browser/browserApi';
import { SafariApp } from '../browser/safariApp';
import { BrowserApi } from "../browser/browserApi";
import { SafariApp } from "../browser/safariApp";
import CommandsBackground from './commands.background';
import ContextMenusBackground from './contextMenus.background';
import IdleBackground from './idle.background';
import { NativeMessagingBackground } from './nativeMessaging.background';
import NotificationBackground from './notification.background';
import RuntimeBackground from './runtime.background';
import TabsBackground from './tabs.background';
import WebRequestBackground from './webRequest.background';
import WindowsBackground from './windows.background';
import CommandsBackground from "./commands.background";
import ContextMenusBackground from "./contextMenus.background";
import IdleBackground from "./idle.background";
import { NativeMessagingBackground } from "./nativeMessaging.background";
import NotificationBackground from "./notification.background";
import RuntimeBackground from "./runtime.background";
import TabsBackground from "./tabs.background";
import WebRequestBackground from "./webRequest.background";
import WindowsBackground from "./windows.background";
import { StateService as StateServiceAbstraction } from '../services/abstractions/state.service';
import { StateService as StateServiceAbstraction } from "../services/abstractions/state.service";
import { Utils } from 'jslib-common/misc/utils';
import { PopupUtilsService } from '../popup/services/popup-utils.service';
import AutofillService from '../services/autofill.service';
import { BrowserCryptoService } from '../services/browserCrypto.service';
import BrowserMessagingService from '../services/browserMessaging.service';
import BrowserPlatformUtilsService from '../services/browserPlatformUtils.service';
import BrowserStorageService from '../services/browserStorage.service';
import I18nService from '../services/i18n.service';
import { StateService } from '../services/state.service';
import VaultTimeoutService from '../services/vaultTimeout.service';
import { Utils } from "jslib-common/misc/utils";
import { PopupUtilsService } from "../popup/services/popup-utils.service";
import AutofillService from "../services/autofill.service";
import { BrowserCryptoService } from "../services/browserCrypto.service";
import BrowserMessagingService from "../services/browserMessaging.service";
import BrowserPlatformUtilsService from "../services/browserPlatformUtils.service";
import BrowserStorageService from "../services/browserStorage.service";
import I18nService from "../services/i18n.service";
import { StateService } from "../services/state.service";
import VaultTimeoutService from "../services/vaultTimeout.service";
export default class MainBackground {
messagingService: MessagingServiceAbstraction;
@ -159,9 +159,19 @@ export default class MainBackground {
this.storageService = new BrowserStorageService();
this.secureStorageService = new BrowserStorageService();
this.logService = new ConsoleLogService(false);
this.stateMigrationService = new StateMigrationService(this.storageService, this.secureStorageService);
this.stateService = new StateService(this.storageService, this.secureStorageService, this.logService, this.stateMigrationService);
this.platformUtilsService = new BrowserPlatformUtilsService(this.messagingService, this.stateService,
this.stateMigrationService = new StateMigrationService(
this.storageService,
this.secureStorageService
);
this.stateService = new StateService(
this.storageService,
this.secureStorageService,
this.logService,
this.stateMigrationService
);
this.platformUtilsService = new BrowserPlatformUtilsService(
this.messagingService,
this.stateService,
(clipboardValue, clearMs) => {
if (this.systemService != null) {
this.systemService.clearClipboard(clipboardValue, clearMs);
@ -172,42 +182,79 @@ export default class MainBackground {
const promise = this.nativeMessagingBackground.getResponse();
try {
await this.nativeMessagingBackground.send({ command: 'biometricUnlock' });
await this.nativeMessagingBackground.send({ command: "biometricUnlock" });
} catch (e) {
return Promise.reject(e);
}
return promise.then(result => result.response === 'unlocked');
return promise.then((result) => result.response === "unlocked");
}
});
}
);
this.i18nService = new I18nService(BrowserApi.getUILanguage(window));
this.cryptoFunctionService = new WebCryptoFunctionService(window, this.platformUtilsService);
this.cryptoService = new BrowserCryptoService(this.cryptoFunctionService, this.platformUtilsService,
this.logService, this.stateService);
this.cryptoService = new BrowserCryptoService(
this.cryptoFunctionService,
this.platformUtilsService,
this.logService,
this.stateService
);
this.tokenService = new TokenService(this.stateService);
this.appIdService = new AppIdService(this.storageService);
this.environmentService = new EnvironmentService(this.stateService);
this.apiService = new ApiService(this.tokenService, this.platformUtilsService, this.environmentService,
(expired: boolean) => this.logout(expired));
this.apiService = new ApiService(
this.tokenService,
this.platformUtilsService,
this.environmentService,
(expired: boolean) => this.logout(expired)
);
this.settingsService = new SettingsService(this.stateService);
this.fileUploadService = new FileUploadService(this.logService, this.apiService);
this.cipherService = new CipherService(this.cryptoService, this.settingsService,
this.apiService, this.fileUploadService,
this.i18nService, () => this.searchService,
this.logService, this.stateService);
this.folderService = new FolderService(this.cryptoService, this.apiService,
this.i18nService, this.cipherService,
this.stateService);
this.collectionService = new CollectionService(this.cryptoService, this.i18nService,
this.stateService);
this.cipherService = new CipherService(
this.cryptoService,
this.settingsService,
this.apiService,
this.fileUploadService,
this.i18nService,
() => this.searchService,
this.logService,
this.stateService
);
this.folderService = new FolderService(
this.cryptoService,
this.apiService,
this.i18nService,
this.cipherService,
this.stateService
);
this.collectionService = new CollectionService(
this.cryptoService,
this.i18nService,
this.stateService
);
this.searchService = new SearchService(this.cipherService, this.logService, this.i18nService);
this.sendService = new SendService(this.cryptoService, this.apiService,
this.fileUploadService, this.i18nService,
this.cryptoFunctionService, this.stateService);
this.sendService = new SendService(
this.cryptoService,
this.apiService,
this.fileUploadService,
this.i18nService,
this.cryptoFunctionService,
this.stateService
);
this.organizationService = new OrganizationService(this.stateService);
this.policyService = new PolicyService(this.stateService, this.organizationService, this.apiService);
this.keyConnectorService = new KeyConnectorService(this.stateService, this.cryptoService,
this.apiService, this.tokenService, this.logService, this.organizationService);
this.policyService = new PolicyService(
this.stateService,
this.organizationService,
this.apiService
);
this.keyConnectorService = new KeyConnectorService(
this.stateService,
this.cryptoService,
this.apiService,
this.tokenService,
this.logService,
this.organizationService
);
const vaultTimeoutServiceCallbacks = {
locked: async () => {
@ -223,7 +270,8 @@ export default class MainBackground {
},
logout: async () => await this.logout(false),
};
this.vaultTimeoutService = new VaultTimeoutService(this.cipherService,
this.vaultTimeoutService = new VaultTimeoutService(
this.cipherService,
this.folderService,
this.collectionService,
this.cryptoService,
@ -233,85 +281,182 @@ export default class MainBackground {
this.tokenService,
this.policyService,
this.keyConnectorService,
this.stateService, vaultTimeoutServiceCallbacks.locked, vaultTimeoutServiceCallbacks.logout);
this.stateService,
vaultTimeoutServiceCallbacks.locked,
vaultTimeoutServiceCallbacks.logout
);
this.providerService = new ProviderService(this.stateService);
this.syncService = new SyncService(this.apiService, this.settingsService,
this.folderService, this.cipherService,
this.cryptoService, this.collectionService,
this.messagingService, this.policyService,
this.sendService, this.logService, this.keyConnectorService,
this.stateService, this.organizationService,
this.providerService, async (expired: boolean) => await this.logout(expired));
this.eventService = new EventService(this.apiService, this.cipherService,
this.stateService, this.logService, this.organizationService);
this.passwordGenerationService = new PasswordGenerationService(this.cryptoService, this.policyService,
this.stateService);
this.totpService = new TotpService(this.cryptoFunctionService, this.logService, this.stateService);
this.autofillService = new AutofillService(this.cipherService, this.stateService,
this.totpService, this.eventService, this.logService);
this.syncService = new SyncService(
this.apiService,
this.settingsService,
this.folderService,
this.cipherService,
this.cryptoService,
this.collectionService,
this.messagingService,
this.policyService,
this.sendService,
this.logService,
this.keyConnectorService,
this.stateService,
this.organizationService,
this.providerService,
async (expired: boolean) => await this.logout(expired)
);
this.eventService = new EventService(
this.apiService,
this.cipherService,
this.stateService,
this.logService,
this.organizationService
);
this.passwordGenerationService = new PasswordGenerationService(
this.cryptoService,
this.policyService,
this.stateService
);
this.totpService = new TotpService(
this.cryptoFunctionService,
this.logService,
this.stateService
);
this.autofillService = new AutofillService(
this.cipherService,
this.stateService,
this.totpService,
this.eventService,
this.logService
);
this.containerService = new ContainerService(this.cryptoService);
this.auditService = new AuditService(this.cryptoFunctionService, this.apiService);
this.exportService = new ExportService(this.folderService, this.cipherService, this.apiService,
this.cryptoService);
this.notificationsService = new NotificationsService(this.syncService, this.appIdService,
this.apiService, this.vaultTimeoutService,
this.environmentService, () => this.logout(true),
this.logService, this.stateService);
this.exportService = new ExportService(
this.folderService,
this.cipherService,
this.apiService,
this.cryptoService
);
this.notificationsService = new NotificationsService(
this.syncService,
this.appIdService,
this.apiService,
this.vaultTimeoutService,
this.environmentService,
() => this.logout(true),
this.logService,
this.stateService
);
this.popupUtilsService = new PopupUtilsService(this.platformUtilsService);
const systemUtilsServiceReloadCallback = () => {
const forceWindowReload = this.platformUtilsService.isSafari() ||
this.platformUtilsService.isFirefox() || this.platformUtilsService.isOpera();
const forceWindowReload =
this.platformUtilsService.isSafari() ||
this.platformUtilsService.isFirefox() ||
this.platformUtilsService.isOpera();
BrowserApi.reloadExtension(forceWindowReload ? window : null);
return Promise.resolve();
};
this.systemService = new SystemService(
this.messagingService, this.platformUtilsService, systemUtilsServiceReloadCallback, this.stateService);
this.messagingService,
this.platformUtilsService,
systemUtilsServiceReloadCallback,
this.stateService
);
// Other fields
this.isSafari = this.platformUtilsService.isSafari();
this.sidebarAction = this.isSafari ? null : (typeof opr !== 'undefined') && opr.sidebarAction ?
opr.sidebarAction : (window as any).chrome.sidebarAction;
this.sidebarAction = this.isSafari
? null
: typeof opr !== "undefined" && opr.sidebarAction
? opr.sidebarAction
: (window as any).chrome.sidebarAction;
// Background
this.runtimeBackground = new RuntimeBackground(this, this.autofillService,
this.runtimeBackground = new RuntimeBackground(
this,
this.autofillService,
this.platformUtilsService as BrowserPlatformUtilsService,
this.i18nService, this.notificationsService,
this.systemService, this.environmentService,
this.messagingService, this.stateService, this.logService);
this.nativeMessagingBackground = new NativeMessagingBackground(this.cryptoService,
this.cryptoFunctionService, this.runtimeBackground,
this.i18nService, this.messagingService, this.appIdService,
this.platformUtilsService, this.stateService);
this.commandsBackground = new CommandsBackground(this, this.passwordGenerationService,
this.platformUtilsService, this.vaultTimeoutService);
this.notificationBackground = new NotificationBackground(this, this.autofillService, this.cipherService,
this.storageService, this.vaultTimeoutService, this.policyService, this.folderService, this.stateService);
this.i18nService,
this.notificationsService,
this.systemService,
this.environmentService,
this.messagingService,
this.stateService,
this.logService
);
this.nativeMessagingBackground = new NativeMessagingBackground(
this.cryptoService,
this.cryptoFunctionService,
this.runtimeBackground,
this.i18nService,
this.messagingService,
this.appIdService,
this.platformUtilsService,
this.stateService
);
this.commandsBackground = new CommandsBackground(
this,
this.passwordGenerationService,
this.platformUtilsService,
this.vaultTimeoutService
);
this.notificationBackground = new NotificationBackground(
this,
this.autofillService,
this.cipherService,
this.storageService,
this.vaultTimeoutService,
this.policyService,
this.folderService,
this.stateService
);
this.tabsBackground = new TabsBackground(this, this.notificationBackground);
this.contextMenusBackground = new ContextMenusBackground(this, this.cipherService, this.passwordGenerationService,
this.platformUtilsService, this.vaultTimeoutService, this.eventService, this.totpService);
this.idleBackground = new IdleBackground(this.vaultTimeoutService, this.stateService,
this.notificationsService);
this.webRequestBackground = new WebRequestBackground(this.platformUtilsService, this.cipherService,
this.vaultTimeoutService);
this.contextMenusBackground = new ContextMenusBackground(
this,
this.cipherService,
this.passwordGenerationService,
this.platformUtilsService,
this.vaultTimeoutService,
this.eventService,
this.totpService
);
this.idleBackground = new IdleBackground(
this.vaultTimeoutService,
this.stateService,
this.notificationsService
);
this.webRequestBackground = new WebRequestBackground(
this.platformUtilsService,
this.cipherService,
this.vaultTimeoutService
);
this.windowsBackground = new WindowsBackground(this);
const that = this;
const backgroundMessagingService = new class extends MessagingServiceAbstraction {
const backgroundMessagingService = new (class extends MessagingServiceAbstraction {
// AuthService should send the messages to the background not popup.
send = (subscriber: string, arg: any = {}) => {
const message = Object.assign({}, { command: subscriber }, arg);
that.runtimeBackground.processMessage(message, that, null);
}
}();
};
})();
this.authService = new AuthService(this.cryptoService, this.apiService,
this.tokenService, this.appIdService,
this.i18nService, this.platformUtilsService,
backgroundMessagingService, this.vaultTimeoutService,
this.logService, this.cryptoFunctionService, this.keyConnectorService, this.environmentService, this.stateService);
this.authService = new AuthService(
this.cryptoService,
this.apiService,
this.tokenService,
this.appIdService,
this.i18nService,
this.platformUtilsService,
backgroundMessagingService,
this.vaultTimeoutService,
this.logService,
this.cryptoFunctionService,
this.keyConnectorService,
this.environmentService,
this.stateService
);
}
async bootstrap() {
@ -332,7 +477,7 @@ export default class MainBackground {
await this.webRequestBackground.init();
await this.windowsBackground.init();
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
setTimeout(async () => {
await this.environmentService.setUrlsFromStorage();
await this.setIcon();
@ -351,11 +496,11 @@ export default class MainBackground {
const isAuthenticated = await this.stateService.getIsAuthenticated();
const locked = await this.vaultTimeoutService.isLocked();
let suffix = '';
let suffix = "";
if (!isAuthenticated) {
suffix = '_gray';
suffix = "_gray";
} else if (locked) {
suffix = '_locked';
suffix = "_locked";
}
await this.actionSetIcon(chrome.browserAction, suffix);
@ -406,7 +551,7 @@ export default class MainBackground {
]);
this.searchService.clearIndex();
this.messagingService.send('doneLoggingOut', { expired: expired });
this.messagingService.send("doneLoggingOut", { expired: expired });
await this.setIcon();
await this.refreshBadgeAndMenu();
@ -426,11 +571,15 @@ export default class MainBackground {
options.frameId = frameId;
}
BrowserApi.tabSendMessage(tab, {
command: 'collectPageDetails',
BrowserApi.tabSendMessage(
tab,
{
command: "collectPageDetails",
tab: tab,
sender: sender,
}, options);
},
options
);
}
async openPopup() {
@ -440,12 +589,15 @@ export default class MainBackground {
if (!this.isSafari) {
return;
}
await SafariApp.sendMessageToApp('showPopover', null, true);
await SafariApp.sendMessageToApp("showPopover", null, true);
}
async reseedStorage() {
if (!this.platformUtilsService.isChrome() && !this.platformUtilsService.isVivaldi() &&
!this.platformUtilsService.isOpera()) {
if (
!this.platformUtilsService.isChrome() &&
!this.platformUtilsService.isVivaldi() &&
!this.platformUtilsService.isOpera()
) {
return;
}
@ -454,11 +606,13 @@ export default class MainBackground {
return;
}
const getStorage = (): Promise<any> => new Promise(resolve => {
const getStorage = (): Promise<any> =>
new Promise((resolve) => {
chrome.storage.local.get(null, (o: any) => resolve(o));
});
const clearStorage = (): Promise<void> => new Promise(resolve => {
const clearStorage = (): Promise<void> =>
new Promise((resolve) => {
chrome.storage.local.clear(() => resolve());
});
@ -482,65 +636,65 @@ export default class MainBackground {
await this.contextMenusRemoveAll();
await this.contextMenusCreate({
type: 'normal',
id: 'root',
contexts: ['all'],
title: 'Bitwarden',
type: "normal",
id: "root",
contexts: ["all"],
title: "Bitwarden",
});
await this.contextMenusCreate({
type: 'normal',
id: 'autofill',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('autoFill'),
type: "normal",
id: "autofill",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("autoFill"),
});
await this.contextMenusCreate({
type: 'normal',
id: 'copy-username',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('copyUsername'),
type: "normal",
id: "copy-username",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("copyUsername"),
});
await this.contextMenusCreate({
type: 'normal',
id: 'copy-password',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('copyPassword'),
type: "normal",
id: "copy-password",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("copyPassword"),
});
if (await this.stateService.getCanAccessPremium()) {
await this.contextMenusCreate({
type: 'normal',
id: 'copy-totp',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('copyVerificationCode'),
type: "normal",
id: "copy-totp",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("copyVerificationCode"),
});
}
await this.contextMenusCreate({
type: 'separator',
parentId: 'root',
type: "separator",
parentId: "root",
});
await this.contextMenusCreate({
type: 'normal',
id: 'generate-password',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('generatePasswordCopied'),
type: "normal",
id: "generate-password",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("generatePasswordCopied"),
});
await this.contextMenusCreate({
type: 'normal',
id: 'copy-identifier',
parentId: 'root',
contexts: ['all'],
title: this.i18nService.t('copyElementIdentifier'),
type: "normal",
id: "copy-identifier",
parentId: "root",
contexts: ["all"],
title: this.i18nService.t("copyElementIdentifier"),
});
this.buildingContextMenu = false;
@ -573,18 +727,18 @@ export default class MainBackground {
}
const disableBadgeCounter = await this.stateService.getDisableBadgeCounter();
let theText = '';
let theText = "";
if (!disableBadgeCounter) {
if (ciphers.length > 0 && ciphers.length <= 9) {
theText = ciphers.length.toString();
} else if (ciphers.length > 0) {
theText = '9+';
theText = "9+";
}
}
if (contextMenuEnabled && ciphers.length === 0) {
await this.loadNoLoginsContextMenuOptions(this.i18nService.t('noMatchingLogins'));
await this.loadNoLoginsContextMenuOptions(this.i18nService.t("noMatchingLogins"));
}
this.sidebarActionSetBadgeText(theText, tabId);
@ -602,88 +756,100 @@ export default class MainBackground {
private async loadMenuAndUpdateBadgeForNoAccessState(contextMenuEnabled: boolean) {
if (contextMenuEnabled) {
const authed = await this.stateService.getIsAuthenticated();
await this.loadNoLoginsContextMenuOptions(this.i18nService.t(authed ? 'vaultLocked' : 'vaultLoggedOut'));
await this.loadNoLoginsContextMenuOptions(
this.i18nService.t(authed ? "vaultLocked" : "vaultLoggedOut")
);
}
const tabs = await BrowserApi.getActiveTabs();
if (tabs != null) {
tabs.forEach(tab => {
tabs.forEach((tab) => {
if (tab.id != null) {
this.browserActionSetBadgeText('', tab.id);
this.sidebarActionSetBadgeText('', tab.id);
this.browserActionSetBadgeText("", tab.id);
this.sidebarActionSetBadgeText("", tab.id);
}
});
}
}
private async loadLoginContextMenuOptions(cipher: any) {
if (cipher == null || cipher.type !== CipherType.Login || cipher.reprompt !== CipherRepromptType.None) {
if (
cipher == null ||
cipher.type !== CipherType.Login ||
cipher.reprompt !== CipherRepromptType.None
) {
return;
}
let title = cipher.name;
if (cipher.login.username && cipher.login.username !== '') {
title += (' (' + cipher.login.username + ')');
if (cipher.login.username && cipher.login.username !== "") {
title += " (" + cipher.login.username + ")";
}
await this.loadContextMenuOptions(title, cipher.id, cipher);
}
private async loadNoLoginsContextMenuOptions(noLoginsMessage: string) {
await this.loadContextMenuOptions(noLoginsMessage, 'noop', null);
await this.loadContextMenuOptions(noLoginsMessage, "noop", null);
}
private async loadContextMenuOptions(title: string, idSuffix: string, cipher: any) {
if (!chrome.contextMenus || this.menuOptionsLoaded.indexOf(idSuffix) > -1 ||
(cipher != null && cipher.type !== CipherType.Login)) {
if (
!chrome.contextMenus ||
this.menuOptionsLoaded.indexOf(idSuffix) > -1 ||
(cipher != null && cipher.type !== CipherType.Login)
) {
return;
}
this.menuOptionsLoaded.push(idSuffix);
if (cipher == null || (cipher.login.password && cipher.login.password !== '')) {
if (cipher == null || (cipher.login.password && cipher.login.password !== "")) {
await this.contextMenusCreate({
type: 'normal',
id: 'autofill_' + idSuffix,
parentId: 'autofill',
contexts: ['all'],
type: "normal",
id: "autofill_" + idSuffix,
parentId: "autofill",
contexts: ["all"],
title: this.sanitizeContextMenuTitle(title),
});
}
if (cipher == null || (cipher.login.username && cipher.login.username !== '')) {
if (cipher == null || (cipher.login.username && cipher.login.username !== "")) {
await this.contextMenusCreate({
type: 'normal',
id: 'copy-username_' + idSuffix,
parentId: 'copy-username',
contexts: ['all'],
type: "normal",
id: "copy-username_" + idSuffix,
parentId: "copy-username",
contexts: ["all"],
title: this.sanitizeContextMenuTitle(title),
});
}
if (cipher == null || (cipher.login.password && cipher.login.password !== '' && cipher.viewPassword)) {
if (
cipher == null ||
(cipher.login.password && cipher.login.password !== "" && cipher.viewPassword)
) {
await this.contextMenusCreate({
type: 'normal',
id: 'copy-password_' + idSuffix,
parentId: 'copy-password',
contexts: ['all'],
type: "normal",
id: "copy-password_" + idSuffix,
parentId: "copy-password",
contexts: ["all"],
title: this.sanitizeContextMenuTitle(title),
});
}
const canAccessPremium = await this.stateService.getCanAccessPremium();
if (canAccessPremium && (cipher == null || (cipher.login.totp && cipher.login.totp !== ''))) {
if (canAccessPremium && (cipher == null || (cipher.login.totp && cipher.login.totp !== ""))) {
await this.contextMenusCreate({
type: 'normal',
id: 'copy-totp_' + idSuffix,
parentId: 'copy-totp',
contexts: ['all'],
type: "normal",
id: "copy-totp_" + idSuffix,
parentId: "copy-totp",
contexts: ["all"],
title: this.sanitizeContextMenuTitle(title),
});
}
}
private sanitizeContextMenuTitle(title: string): string {
return title.replace(/&/g, '&&');
return title.replace(/&/g, "&&");
}
private async fullSync(override: boolean = false) {
@ -711,11 +877,10 @@ export default class MainBackground {
this.syncTimeout = setTimeout(async () => await this.fullSync(), 5 * 60 * 1000); // check every 5 minutes
}
// Browser API Helpers
private contextMenusRemoveAll() {
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
chrome.contextMenus.removeAll(() => {
resolve();
if (chrome.runtime.lastError) {
@ -726,7 +891,7 @@ export default class MainBackground {
}
private contextMenusCreate(options: any) {
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
chrome.contextMenus.create(options, () => {
resolve();
if (chrome.runtime.lastError) {
@ -743,8 +908,8 @@ export default class MainBackground {
const options = {
path: {
19: 'images/icon19' + suffix + '.png',
38: 'images/icon38' + suffix + '.png',
19: "images/icon19" + suffix + ".png",
38: "images/icon38" + suffix + ".png",
},
};
@ -755,7 +920,7 @@ export default class MainBackground {
// which doesn't resolve within a reasonable time.
theAction.setIcon(options);
} else {
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
theAction.setIcon(options, () => resolve());
});
}
@ -763,7 +928,7 @@ export default class MainBackground {
private actionSetBadgeBackgroundColor(action: any) {
if (action && action.setBadgeBackgroundColor) {
action.setBadgeBackgroundColor({ color: '#294e5f' });
action.setBadgeBackgroundColor({ color: "#294e5f" });
}
}
@ -787,9 +952,9 @@ export default class MainBackground {
tabId: tabId,
});
} else if (this.sidebarAction.setTitle) {
let title = 'Bitwarden';
if (text && text !== '') {
title += (' [' + text + ']');
let title = "Bitwarden";
if (text && text !== "") {
title += " [" + text + "]";
}
this.sidebarAction.setTitle({

View File

@ -1,20 +1,20 @@
import { AppIdService } from 'jslib-common/abstractions/appId.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { CryptoFunctionService } from 'jslib-common/abstractions/cryptoFunction.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StateService } from 'jslib-common/abstractions/state.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { AppIdService } from "jslib-common/abstractions/appId.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StateService } from "jslib-common/abstractions/state.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { Utils } from 'jslib-common/misc/utils';
import { SymmetricCryptoKey } from 'jslib-common/models/domain/symmetricCryptoKey';
import { Utils } from "jslib-common/misc/utils";
import { SymmetricCryptoKey } from "jslib-common/models/domain/symmetricCryptoKey";
import { BrowserApi } from '../browser/browserApi';
import RuntimeBackground from './runtime.background';
import { BrowserApi } from "../browser/browserApi";
import RuntimeBackground from "./runtime.background";
const MessageValidTimeout = 10 * 1000;
const EncryptionAlgorithm = 'sha1';
const EncryptionAlgorithm = "sha1";
export class NativeMessagingBackground {
private connected = false;
@ -29,16 +29,21 @@ export class NativeMessagingBackground {
private appId: string;
private validatingFingerprint: boolean;
constructor(private cryptoService: CryptoService,
constructor(
private cryptoService: CryptoService,
private cryptoFunctionService: CryptoFunctionService,
private runtimeBackground: RuntimeBackground, private i18nService: I18nService,
private messagingService: MessagingService, private appIdService: AppIdService,
private platformUtilsService: PlatformUtilsService, private stateService: StateService) {
private runtimeBackground: RuntimeBackground,
private i18nService: I18nService,
private messagingService: MessagingService,
private appIdService: AppIdService,
private platformUtilsService: PlatformUtilsService,
private stateService: StateService
) {
this.stateService.setBiometricFingerprintValidated(false);
if (chrome?.permissions?.onAdded) {
// Reload extension to activate nativeMessaging
chrome.permissions.onAdded.addListener(permissions => {
chrome.permissions.onAdded.addListener((permissions) => {
BrowserApi.reloadExtension(null);
});
}
@ -49,7 +54,7 @@ export class NativeMessagingBackground {
this.stateService.setBiometricFingerprintValidated(false);
return new Promise<void>((resolve, reject) => {
this.port = BrowserApi.connectNative('com.8bit.bitwarden');
this.port = BrowserApi.connectNative("com.8bit.bitwarden");
this.connecting = true;
@ -67,30 +72,34 @@ export class NativeMessagingBackground {
this.port.onMessage.addListener(async (message: any) => {
switch (message.command) {
case 'connected':
case "connected":
connectedCallback();
break;
case 'disconnected':
case "disconnected":
if (this.connecting) {
this.messagingService.send('showDialog', {
text: this.i18nService.t('startDesktopDesc'),
title: this.i18nService.t('startDesktopTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
this.messagingService.send("showDialog", {
text: this.i18nService.t("startDesktopDesc"),
title: this.i18nService.t("startDesktopTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
reject();
}
this.connected = false;
this.port.disconnect();
break;
case 'setupEncryption':
case "setupEncryption":
// Ignore since it belongs to another device
if (message.appId !== this.appId) {
return;
}
const encrypted = Utils.fromB64ToArray(message.sharedSecret);
const decrypted = await this.cryptoFunctionService.rsaDecrypt(encrypted.buffer, this.privateKey, EncryptionAlgorithm);
const decrypted = await this.cryptoFunctionService.rsaDecrypt(
encrypted.buffer,
this.privateKey,
EncryptionAlgorithm
);
if (this.validatingFingerprint) {
this.validatingFingerprint = false;
@ -99,7 +108,7 @@ export class NativeMessagingBackground {
this.sharedSecret = new SymmetricCryptoKey(decrypted);
this.secureSetupResolve();
break;
case 'invalidateEncryption':
case "invalidateEncryption":
// Ignore since it belongs to another device
if (message.appId !== this.appId) {
return;
@ -109,21 +118,21 @@ export class NativeMessagingBackground {
this.privateKey = null;
this.connected = false;
this.messagingService.send('showDialog', {
text: this.i18nService.t('nativeMessagingInvalidEncryptionDesc'),
title: this.i18nService.t('nativeMessagingInvalidEncryptionTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
this.messagingService.send("showDialog", {
text: this.i18nService.t("nativeMessagingInvalidEncryptionDesc"),
title: this.i18nService.t("nativeMessagingInvalidEncryptionTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
break;
case 'verifyFingerprint': {
case "verifyFingerprint": {
if (this.sharedSecret == null) {
this.validatingFingerprint = true;
this.showFingerprintDialog();
}
break;
}
case 'wrongUserId':
case "wrongUserId":
this.showWrongUserDialog();
default:
// Ignore since it belongs to another device
@ -144,11 +153,11 @@ export class NativeMessagingBackground {
}
if (error != null) {
this.messagingService.send('showDialog', {
text: this.i18nService.t('desktopIntegrationDisabledDesc'),
title: this.i18nService.t('desktopIntegrationDisabledTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
this.messagingService.send("showDialog", {
text: this.i18nService.t("desktopIntegrationDisabledDesc"),
title: this.i18nService.t("desktopIntegrationDisabledTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
}
this.sharedSecret = null;
@ -160,11 +169,11 @@ export class NativeMessagingBackground {
}
showWrongUserDialog() {
this.messagingService.send('showDialog', {
text: this.i18nService.t('nativeMessagingWrongUserDesc'),
title: this.i18nService.t('nativeMessagingWrongUserTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
this.messagingService.send("showDialog", {
text: this.i18nService.t("nativeMessagingWrongUserDesc"),
title: this.i18nService.t("nativeMessagingWrongUserTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
}
@ -208,11 +217,11 @@ export class NativeMessagingBackground {
this.privateKey = null;
this.connected = false;
this.messagingService.send('showDialog', {
text: this.i18nService.t('nativeMessagingInvalidEncryptionDesc'),
title: this.i18nService.t('nativeMessagingInvalidEncryptionTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
this.messagingService.send("showDialog", {
text: this.i18nService.t("nativeMessagingInvalidEncryptionDesc"),
title: this.i18nService.t("nativeMessagingInvalidEncryptionTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
}
}
@ -225,35 +234,35 @@ export class NativeMessagingBackground {
if (Math.abs(message.timestamp - Date.now()) > MessageValidTimeout) {
// tslint:disable-next-line
console.error('NativeMessage is to old, ignoring.');
console.error("NativeMessage is to old, ignoring.");
return;
}
switch (message.command) {
case 'biometricUnlock':
case "biometricUnlock":
await this.stateService.setBiometricAwaitingAcceptance(null);
if (message.response === 'not enabled') {
this.messagingService.send('showDialog', {
text: this.i18nService.t('biometricsNotEnabledDesc'),
title: this.i18nService.t('biometricsNotEnabledTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
if (message.response === "not enabled") {
this.messagingService.send("showDialog", {
text: this.i18nService.t("biometricsNotEnabledDesc"),
title: this.i18nService.t("biometricsNotEnabledTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
break;
} else if (message.response === 'not supported') {
this.messagingService.send('showDialog', {
text: this.i18nService.t('biometricsNotSupportedDesc'),
title: this.i18nService.t('biometricsNotSupportedTitle'),
confirmText: this.i18nService.t('ok'),
type: 'error',
} else if (message.response === "not supported") {
this.messagingService.send("showDialog", {
text: this.i18nService.t("biometricsNotSupportedDesc"),
title: this.i18nService.t("biometricsNotSupportedTitle"),
confirmText: this.i18nService.t("ok"),
type: "error",
});
break;
}
const enabled = await this.stateService.getBiometricUnlock();
if (enabled === null || enabled === false) {
if (message.response === 'unlocked') {
if (message.response === "unlocked") {
await this.stateService.setBiometricUnlock(true);
}
break;
@ -264,15 +273,17 @@ export class NativeMessagingBackground {
break;
}
if (message.response === 'unlocked') {
await this.cryptoService.setKey(new SymmetricCryptoKey(Utils.fromB64ToArray(message.keyB64).buffer));
if (message.response === "unlocked") {
await this.cryptoService.setKey(
new SymmetricCryptoKey(Utils.fromB64ToArray(message.keyB64).buffer)
);
// Verify key is correct by attempting to decrypt a secret
try {
await this.cryptoService.getFingerprint(await this.stateService.getUserId());
} catch (e) {
// tslint:disable-next-line
console.error('Unable to verify key:', e);
console.error("Unable to verify key:", e);
await this.cryptoService.clearKey();
this.showWrongUserDialog();
@ -281,12 +292,12 @@ export class NativeMessagingBackground {
}
await this.stateService.setBiometricLocked(false);
this.runtimeBackground.processMessage({ command: 'unlocked' }, null, null);
this.runtimeBackground.processMessage({ command: "unlocked" }, null, null);
}
break;
default:
// tslint:disable-next-line
console.error('NativeMessage, got unknown command: ', message.command);
console.error("NativeMessage, got unknown command: ", message.command);
}
if (this.resolver) {
@ -300,12 +311,12 @@ export class NativeMessagingBackground {
this.privateKey = privateKey;
this.sendUnencrypted({
command: 'setupEncryption',
command: "setupEncryption",
publicKey: Utils.fromBufferToB64(publicKey),
userId: await this.stateService.getUserId(),
});
return new Promise((resolve, reject) => this.secureSetupResolve = resolve);
return new Promise((resolve, reject) => (this.secureSetupResolve = resolve));
}
private async sendUnencrypted(message: any) {
@ -319,13 +330,17 @@ export class NativeMessagingBackground {
}
private async showFingerprintDialog() {
const fingerprint = (await this.cryptoService.getFingerprint(await this.stateService.getUserId(), this.publicKey)).join(' ');
const fingerprint = (
await this.cryptoService.getFingerprint(await this.stateService.getUserId(), this.publicKey)
).join(" ");
this.messagingService.send('showDialog', {
html: `${this.i18nService.t('desktopIntegrationVerificationText')}<br><br><strong>${fingerprint}</strong>`,
title: this.i18nService.t('desktopSyncVerificationTitle'),
confirmText: this.i18nService.t('ok'),
type: 'warning',
this.messagingService.send("showDialog", {
html: `${this.i18nService.t(
"desktopIntegrationVerificationText"
)}<br><br><strong>${fingerprint}</strong>`,
title: this.i18nService.t("desktopSyncVerificationTitle"),
confirmText: this.i18nService.t("ok"),
type: "warning",
});
}
}

View File

@ -28,10 +28,7 @@ import LockedVaultPendingNotificationsItem from "./models/lockedVaultPendingNoti
import { NotificationQueueMessageType } from "./models/notificationQueueMessageType";
export default class NotificationBackground {
private notificationQueue: (
| AddLoginQueueMessage
| AddChangePasswordQueueMessage
)[] = [];
private notificationQueue: (AddLoginQueueMessage | AddChangePasswordQueueMessage)[] = [];
constructor(
private main: MainBackground,
@ -65,26 +62,16 @@ export default class NotificationBackground {
if (msg.data.target !== "notification.background") {
return;
}
await this.processMessage(
msg.data.commandToRetry.msg,
msg.data.commandToRetry.sender
);
await this.processMessage(msg.data.commandToRetry.msg, msg.data.commandToRetry.sender);
break;
case "bgGetDataForTab":
await this.getDataForTab(sender.tab, msg.responseCommand);
break;
case "bgCloseNotificationBar":
await BrowserApi.tabSendMessageData(
sender.tab,
"closeNotificationBar"
);
await BrowserApi.tabSendMessageData(sender.tab, "closeNotificationBar");
break;
case "bgAdjustNotificationBar":
await BrowserApi.tabSendMessageData(
sender.tab,
"adjustNotificationBar",
msg.data
);
await BrowserApi.tabSendMessageData(sender.tab, "adjustNotificationBar", msg.data);
break;
case "bgAddLogin":
await this.addLogin(msg.login, sender.tab);
@ -111,10 +98,7 @@ export default class NotificationBackground {
"addToLockedVaultPendingNotifications",
retryMessage
);
await BrowserApi.tabSendMessageData(
sender.tab,
"promptForLogin"
);
await BrowserApi.tabSendMessageData(sender.tab, "promptForLogin");
return;
}
await this.saveOrUpdateCredentials(sender.tab, msg.folder);
@ -125,18 +109,11 @@ export default class NotificationBackground {
case "collectPageDetailsResponse":
switch (msg.sender) {
case "notificationBar":
const forms =
this.autofillService.getFormsWithPasswordFields(
msg.details
);
await BrowserApi.tabSendMessageData(
msg.tab,
"notificationBarPageDetails",
{
const forms = this.autofillService.getFormsWithPasswordFields(msg.details);
await BrowserApi.tabSendMessageData(msg.tab, "notificationBarPageDetails", {
details: msg.details,
forms: forms,
}
);
});
break;
default:
break;
@ -190,20 +167,14 @@ export default class NotificationBackground {
continue;
}
if (
this.notificationQueue[i].type ===
NotificationQueueMessageType.addLogin
) {
if (this.notificationQueue[i].type === NotificationQueueMessageType.addLogin) {
BrowserApi.tabSendMessageData(tab, "openNotificationBar", {
type: "add",
typeData: {
isVaultLocked: this.notificationQueue[i].wasVaultLocked,
},
});
} else if (
this.notificationQueue[i].type ===
NotificationQueueMessageType.changePassword
) {
} else if (this.notificationQueue[i].type === NotificationQueueMessageType.changePassword) {
BrowserApi.tabSendMessageData(tab, "openNotificationBar", {
type: "change",
typeData: {
@ -223,10 +194,7 @@ export default class NotificationBackground {
}
}
private async addLogin(
loginInfo: AddLoginRuntimeMessage,
tab: chrome.tabs.Tab
) {
private async addLogin(loginInfo: AddLoginRuntimeMessage, tab: chrome.tabs.Tab) {
if (!(await this.stateService.getIsAuthenticated())) {
return;
}
@ -250,17 +218,12 @@ export default class NotificationBackground {
return;
}
const ciphers = await this.cipherService.getAllDecryptedForUrl(
loginInfo.url
);
const ciphers = await this.cipherService.getAllDecryptedForUrl(loginInfo.url);
const usernameMatches = ciphers.filter(
(c) =>
c.login.username != null &&
c.login.username.toLowerCase() === normalizedUsername
(c) => c.login.username != null && c.login.username.toLowerCase() === normalizedUsername
);
if (usernameMatches.length === 0) {
const disabledAddLogin =
await this.stateService.getDisableAddLoginNotification();
const disabledAddLogin = await this.stateService.getDisableAddLoginNotification();
if (disabledAddLogin) {
return;
}
@ -279,12 +242,7 @@ export default class NotificationBackground {
if (disabledChangePassword) {
return;
}
this.pushChangePasswordToQueue(
usernameMatches[0].id,
loginDomain,
loginInfo.password,
tab
);
this.pushChangePasswordToQueue(usernameMatches[0].id, loginDomain, loginInfo.password, tab);
}
}
@ -310,30 +268,19 @@ export default class NotificationBackground {
await this.checkNotificationQueue(tab);
}
private async changedPassword(
changeData: ChangePasswordRuntimeMessage,
tab: chrome.tabs.Tab
) {
private async changedPassword(changeData: ChangePasswordRuntimeMessage, tab: chrome.tabs.Tab) {
const loginDomain = Utils.getDomain(changeData.url);
if (loginDomain == null) {
return;
}
if (await this.vaultTimeoutService.isLocked()) {
this.pushChangePasswordToQueue(
null,
loginDomain,
changeData.newPassword,
tab,
true
);
this.pushChangePasswordToQueue(null, loginDomain, changeData.newPassword, tab, true);
return;
}
let id: string = null;
const ciphers = await this.cipherService.getAllDecryptedForUrl(
changeData.url
);
const ciphers = await this.cipherService.getAllDecryptedForUrl(changeData.url);
if (changeData.currentPassword != null) {
const passwordMatches = ciphers.filter(
(c) => c.login.password === changeData.currentPassword
@ -345,12 +292,7 @@ export default class NotificationBackground {
id = ciphers[0].id;
}
if (id != null) {
this.pushChangePasswordToQueue(
id,
loginDomain,
changeData.newPassword,
tab
);
this.pushChangePasswordToQueue(id, loginDomain, changeData.newPassword, tab);
}
}
@ -376,17 +318,13 @@ export default class NotificationBackground {
await this.checkNotificationQueue(tab);
}
private async saveOrUpdateCredentials(
tab: chrome.tabs.Tab,
folderId?: string
) {
private async saveOrUpdateCredentials(tab: chrome.tabs.Tab, folderId?: string) {
for (let i = this.notificationQueue.length - 1; i >= 0; i--) {
const queueMessage = this.notificationQueue[i];
if (
queueMessage.tabId !== tab.id ||
(queueMessage.type !== NotificationQueueMessageType.addLogin &&
queueMessage.type !==
NotificationQueueMessageType.changePassword)
queueMessage.type !== NotificationQueueMessageType.changePassword)
) {
continue;
}
@ -399,14 +337,9 @@ export default class NotificationBackground {
this.notificationQueue.splice(i, 1);
BrowserApi.tabSendMessageData(tab, "closeNotificationBar");
if (
queueMessage.type ===
NotificationQueueMessageType.changePassword
) {
if (queueMessage.type === NotificationQueueMessageType.changePassword) {
const message = queueMessage as AddChangePasswordQueueMessage;
const cipher = await this.getDecryptedCipherById(
message.cipherId
);
const cipher = await this.getDecryptedCipherById(message.cipherId);
if (cipher == null) {
return;
}
@ -415,10 +348,7 @@ export default class NotificationBackground {
}
if (!queueMessage.wasVaultLocked) {
await this.createNewCipher(
queueMessage as AddLoginQueueMessage,
folderId
);
await this.createNewCipher(queueMessage as AddLoginQueueMessage, folderId);
}
// If the vault was locked, check if a cipher needs updating instead of creating a new one
@ -427,20 +357,13 @@ export default class NotificationBackground {
queueMessage.wasVaultLocked === true
) {
const message = queueMessage as AddLoginQueueMessage;
const ciphers = await this.cipherService.getAllDecryptedForUrl(
message.uri
);
const ciphers = await this.cipherService.getAllDecryptedForUrl(message.uri);
const usernameMatches = ciphers.filter(
(c) =>
c.login.username != null &&
c.login.username.toLowerCase() === message.username
(c) => c.login.username != null && c.login.username.toLowerCase() === message.username
);
if (usernameMatches.length >= 1) {
await this.updateCipher(
usernameMatches[0],
message.password
);
await this.updateCipher(usernameMatches[0], message.password);
return;
}
@ -449,10 +372,7 @@ export default class NotificationBackground {
}
}
private async createNewCipher(
queueMessage: AddLoginQueueMessage,
folderId: string
) {
private async createNewCipher(queueMessage: AddLoginQueueMessage, folderId: string) {
const loginModel = new LoginView();
const loginUri = new LoginUriView();
loginUri.uri = queueMessage.uri;
@ -525,8 +445,6 @@ export default class NotificationBackground {
}
private async allowPersonalOwnership(): Promise<boolean> {
return !(await this.policyService.policyAppliesToUser(
PolicyType.PersonalOwnership
));
return !(await this.policyService.policyAppliesToUser(PolicyType.PersonalOwnership));
}
}

View File

@ -1,22 +1,22 @@
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { NotificationsService } from 'jslib-common/abstractions/notifications.service';
import { SystemService } from 'jslib-common/abstractions/system.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { NotificationsService } from "jslib-common/abstractions/notifications.service";
import { SystemService } from "jslib-common/abstractions/system.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { AutofillService } from '../services/abstractions/autofill.service';
import BrowserPlatformUtilsService from '../services/browserPlatformUtils.service';
import { AutofillService } from "../services/abstractions/autofill.service";
import BrowserPlatformUtilsService from "../services/browserPlatformUtils.service";
import { BrowserApi } from '../browser/browserApi';
import { BrowserApi } from "../browser/browserApi";
import MainBackground from './main.background';
import MainBackground from "./main.background";
import { Utils } from 'jslib-common/misc/utils';
import { Utils } from "jslib-common/misc/utils";
import { StateService } from 'jslib-common/abstractions/state.service';
import LockedVaultPendingNotificationsItem from './models/lockedVaultPendingNotificationsItem';
import { StateService } from "jslib-common/abstractions/state.service";
import LockedVaultPendingNotificationsItem from "./models/lockedVaultPendingNotificationsItem";
export default class RuntimeBackground {
private autofillTimeout: any;
@ -24,13 +24,18 @@ export default class RuntimeBackground {
private onInstalledReason: string = null;
private lockedVaultPendingNotifications: LockedVaultPendingNotificationsItem[] = [];
constructor(private main: MainBackground, private autofillService: AutofillService,
constructor(
private main: MainBackground,
private autofillService: AutofillService,
private platformUtilsService: BrowserPlatformUtilsService,
private i18nService: I18nService,
private notificationsService: NotificationsService, private systemService: SystemService,
private environmentService: EnvironmentService, private messagingService: MessagingService,
private stateService: StateService, private logService: LogService) {
private notificationsService: NotificationsService,
private systemService: SystemService,
private environmentService: EnvironmentService,
private messagingService: MessagingService,
private stateService: StateService,
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;
@ -43,15 +48,18 @@ export default class RuntimeBackground {
}
await this.checkOnInstalled();
BrowserApi.messageListener('runtime.background', async (msg: any, sender: chrome.runtime.MessageSender, sendResponse: any) => {
BrowserApi.messageListener(
"runtime.background",
async (msg: any, sender: chrome.runtime.MessageSender, sendResponse: any) => {
await this.processMessage(msg, sender, sendResponse);
});
}
);
}
async processMessage(msg: any, sender: any, sendResponse: any) {
switch (msg.command) {
case 'loggedIn':
case 'unlocked':
case "loggedIn":
case "unlocked":
let item: LockedVaultPendingNotificationsItem;
if (this.lockedVaultPendingNotifications.length > 0) {
@ -65,59 +73,68 @@ export default class RuntimeBackground {
await this.main.setIcon();
await this.main.refreshBadgeAndMenu(false);
this.notificationsService.updateConnection(msg.command === 'unlocked');
this.notificationsService.updateConnection(msg.command === "unlocked");
this.systemService.cancelProcessReload();
if (item) {
await BrowserApi.tabSendMessageData(item.commandToRetry.sender.tab, 'unlockCompleted', item);
await BrowserApi.tabSendMessageData(
item.commandToRetry.sender.tab,
"unlockCompleted",
item
);
}
break;
case 'addToLockedVaultPendingNotifications':
case "addToLockedVaultPendingNotifications":
this.lockedVaultPendingNotifications.push(msg.data);
break;
case 'logout':
case "logout":
await this.main.logout(msg.expired);
break;
case 'syncCompleted':
case "syncCompleted":
if (msg.successfully) {
setTimeout(async () => await this.main.refreshBadgeAndMenu(), 2000);
}
break;
case 'openPopup':
case "openPopup":
await this.main.openPopup();
break;
case 'promptForLogin':
await BrowserApi.createNewTab('popup/index.html?uilocation=popout', true, true);
case "promptForLogin":
await BrowserApi.createNewTab("popup/index.html?uilocation=popout", true, true);
break;
case 'showDialogResolve':
case "showDialogResolve":
this.platformUtilsService.resolveDialogPromise(msg.dialogId, msg.confirmed);
break;
case 'bgCollectPageDetails':
case "bgCollectPageDetails":
await this.main.collectPageDetailsForContentScript(sender.tab, msg.sender, sender.frameId);
break;
case 'bgUpdateContextMenu':
case 'editedCipher':
case 'addedCipher':
case 'deletedCipher':
case "bgUpdateContextMenu":
case "editedCipher":
case "addedCipher":
case "deletedCipher":
await this.main.refreshBadgeAndMenu();
break;
case 'bgReseedStorage':
case "bgReseedStorage":
await this.main.reseedStorage();
break;
case 'collectPageDetailsResponse':
case "collectPageDetailsResponse":
switch (msg.sender) {
case 'autofiller':
case 'autofill_cmd':
const totpCode = await this.autofillService.doAutoFillActiveTab([{
case "autofiller":
case "autofill_cmd":
const totpCode = await this.autofillService.doAutoFillActiveTab(
[
{
frameId: sender.frameId,
tab: msg.tab,
details: msg.details,
}], msg.sender === 'autofill_cmd');
},
],
msg.sender === "autofill_cmd"
);
if (totpCode != null) {
this.platformUtilsService.copyToClipboard(totpCode, { window: window });
}
break;
case 'contextMenu':
case "contextMenu":
clearTimeout(this.autofillTimeout);
this.pageDetailsToAutoFill.push({
frameId: sender.frameId,
@ -130,7 +147,7 @@ export default class RuntimeBackground {
break;
}
break;
case 'authResult':
case "authResult":
const vaultUrl = this.environmentService.getWebVaultUrl();
if (msg.referrer == null || Utils.getHostname(vaultUrl) !== msg.referrer) {
@ -138,37 +155,45 @@ export default class RuntimeBackground {
}
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');
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;
case 'webAuthnResult':
case "webAuthnResult":
const vaultUrl2 = this.environmentService.getWebVaultUrl();
if (msg.referrer == null || Utils.getHostname(vaultUrl2) !== msg.referrer) {
return;
}
const params = `webAuthnResponse=${encodeURIComponent(msg.data)};` +
const params =
`webAuthnResponse=${encodeURIComponent(msg.data)};` +
`remember=${encodeURIComponent(msg.remember)}`;
BrowserApi.createNewTab(`popup/index.html?uilocation=popout#/2fa;${params}`, undefined, false);
BrowserApi.createNewTab(
`popup/index.html?uilocation=popout#/2fa;${params}`,
undefined,
false
);
break;
case 'reloadPopup':
this.messagingService.send('reloadPopup');
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',
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':
case "getClickedElementResponse":
this.platformUtilsService.copyToClipboard(msg.identifier, { window: window });
default:
break;
@ -194,8 +219,8 @@ export default class RuntimeBackground {
private async checkOnInstalled() {
setTimeout(async () => {
if (this.onInstalledReason != null) {
if (this.onInstalledReason === 'install') {
BrowserApi.createNewTab('https://bitwarden.com/browser-start/');
if (this.onInstalledReason === "install") {
BrowserApi.createNewTab("https://bitwarden.com/browser-start/");
await this.setDefaultSettings();
}
@ -214,7 +239,7 @@ export default class RuntimeBackground {
// Default action to "lock".
const currentVaultTimeoutAction = await this.stateService.getVaultTimeoutAction();
if (currentVaultTimeoutAction == null) {
await this.stateService.setVaultTimeoutAction('lock');
await this.stateService.setVaultTimeoutAction("lock");
}
}
}

View File

@ -1,8 +1,8 @@
import { Account as BaseAccount } from 'jslib-common/models/domain/account';
import { Account as BaseAccount } from "jslib-common/models/domain/account";
import { BrowserComponentState } from './browserComponentState';
import { BrowserGroupingsComponentState } from './browserGroupingsComponentState';
import { BrowserSendComponentState } from './browserSendComponentState';
import { BrowserComponentState } from "./browserComponentState";
import { BrowserGroupingsComponentState } from "./browserGroupingsComponentState";
import { BrowserSendComponentState } from "./browserSendComponentState";
export class Account extends BaseAccount {
groupings?: BrowserGroupingsComponentState;
@ -12,13 +12,9 @@ export class Account extends BaseAccount {
constructor(init: Partial<Account>) {
super(init);
this.groupings = init.groupings ??
new BrowserGroupingsComponentState();
this.send = init.send ??
new BrowserSendComponentState();
this.ciphers = init.ciphers ??
new BrowserComponentState();
this.sendType = init.sendType ??
new BrowserComponentState();
this.groupings = init.groupings ?? new BrowserGroupingsComponentState();
this.send = init.send ?? new BrowserSendComponentState();
this.ciphers = init.ciphers ?? new BrowserComponentState();
this.sendType = init.sendType ?? new BrowserComponentState();
}
}

View File

@ -1,8 +1,8 @@
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CollectionView } from 'jslib-common/models/view/collectionView';
import { FolderView } from 'jslib-common/models/view/folderView';
import { BrowserComponentState } from './browserComponentState';
import { CipherType } from "jslib-common/enums/cipherType";
import { CipherView } from "jslib-common/models/view/cipherView";
import { CollectionView } from "jslib-common/models/view/collectionView";
import { FolderView } from "jslib-common/models/view/folderView";
import { BrowserComponentState } from "./browserComponentState";
export class BrowserGroupingsComponentState extends BrowserComponentState {
favoriteCiphers: CipherView[];

View File

@ -1,6 +1,6 @@
import { SendType } from 'jslib-common/enums/sendType';
import { SendView } from 'jslib-common/models/view/sendView';
import { BrowserComponentState } from './browserComponentState';
import { SendType } from "jslib-common/enums/sendType";
import { SendView } from "jslib-common/models/view/sendView";
import { BrowserComponentState } from "./browserComponentState";
export class BrowserSendComponentState extends BrowserComponentState {
sends: SendView[];

View File

@ -1,26 +1,30 @@
import { Component } from '@angular/core';
import { Component } from "@angular/core";
import { CryptoFunctionService } from 'jslib-common/abstractions/cryptoFunction.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StateService } from '../../services/abstractions/state.service';
import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StateService } from "../../services/abstractions/state.service";
import { Utils } from 'jslib-common/misc/utils';
import { Utils } from "jslib-common/misc/utils";
@Component({
selector: 'app-home',
templateUrl: 'home.component.html',
selector: "app-home",
templateUrl: "home.component.html",
})
export class HomeComponent {
constructor(protected platformUtilsService: PlatformUtilsService,
private passwordGenerationService: PasswordGenerationService, private stateService: StateService,
private cryptoFunctionService: CryptoFunctionService, private environmentService: EnvironmentService) { }
constructor(
protected platformUtilsService: PlatformUtilsService,
private passwordGenerationService: PasswordGenerationService,
private stateService: StateService,
private cryptoFunctionService: CryptoFunctionService,
private environmentService: EnvironmentService
) {}
async launchSsoBrowser() {
// Generate necessary sso params
const passwordOptions: any = {
type: 'password',
type: "password",
length: 64,
uppercase: true,
lowercase: true,
@ -28,9 +32,11 @@ export class HomeComponent {
special: false,
};
const state = (await this.passwordGenerationService.generatePassword(passwordOptions)) + ':clientId=browser';
const state =
(await this.passwordGenerationService.generatePassword(passwordOptions)) +
":clientId=browser";
const codeVerifier = await this.passwordGenerationService.generatePassword(passwordOptions);
const codeVerifierHash = await this.cryptoFunctionService.hash(codeVerifier, 'sha256');
const codeVerifierHash = await this.cryptoFunctionService.hash(codeVerifier, "sha256");
const codeChallenge = Utils.fromBufferToUrlB64(codeVerifierHash);
await this.stateService.setSsoCodeVerifier(codeVerifier);
@ -38,14 +44,21 @@ export class HomeComponent {
let url = this.environmentService.getWebVaultUrl();
if (url == null) {
url = 'https://vault.bitwarden.com';
url = "https://vault.bitwarden.com";
}
const redirectUri = url + '/sso-connector.html';
const redirectUri = url + "/sso-connector.html";
// Launch browser
this.platformUtilsService.launchUri(url + '/#/sso?clientId=browser' +
'&redirectUri=' + encodeURIComponent(redirectUri) +
'&state=' + state + '&codeChallenge=' + codeChallenge);
this.platformUtilsService.launchUri(
url +
"/#/sso?clientId=browser" +
"&redirectUri=" +
encodeURIComponent(redirectUri) +
"&state=" +
state +
"&codeChallenge=" +
codeChallenge
);
}
}

View File

@ -1,45 +1,67 @@
import { Component, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { Component, NgZone } from "@angular/core";
import { Router } from "@angular/router";
import Swal from "sweetalert2";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { KeyConnectorService } from 'jslib-common/abstractions/keyConnector.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { KeyConnectorService } from "jslib-common/abstractions/keyConnector.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
import { LockComponent as BaseLockComponent } from 'jslib-angular/components/lock.component';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { LockComponent as BaseLockComponent } from "jslib-angular/components/lock.component";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
@Component({
selector: 'app-lock',
templateUrl: 'lock.component.html',
selector: "app-lock",
templateUrl: "lock.component.html",
})
export class LockComponent extends BaseLockComponent {
private isInitialLockScreen: boolean;
constructor(router: Router, i18nService: I18nService,
platformUtilsService: PlatformUtilsService, messagingService: MessagingService, cryptoService: CryptoService,
vaultTimeoutService: VaultTimeoutService, environmentService: EnvironmentService,
stateService: StateService, apiService: ApiService, logService: LogService, keyConnectorService: KeyConnectorService, ngZone: NgZone) {
super(router, i18nService, platformUtilsService,
messagingService, cryptoService, vaultTimeoutService,
environmentService, stateService, apiService, logService, keyConnectorService, ngZone);
this.successRoute = '/tabs/current';
constructor(
router: Router,
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
messagingService: MessagingService,
cryptoService: CryptoService,
vaultTimeoutService: VaultTimeoutService,
environmentService: EnvironmentService,
stateService: StateService,
apiService: ApiService,
logService: LogService,
keyConnectorService: KeyConnectorService,
ngZone: NgZone
) {
super(
router,
i18nService,
platformUtilsService,
messagingService,
cryptoService,
vaultTimeoutService,
environmentService,
stateService,
apiService,
logService,
keyConnectorService,
ngZone
);
this.successRoute = "/tabs/current";
this.isInitialLockScreen = (window as any).previousPopupUrl == null;
}
async ngOnInit() {
await super.ngOnInit();
const disableAutoBiometricsPrompt = await this.stateService.getDisableAutoBiometricsPrompt() ?? true;
const disableAutoBiometricsPrompt =
(await this.stateService.getDisableAutoBiometricsPrompt()) ?? true;
window.setTimeout(async () => {
document.getElementById(this.pinLock ? 'pin' : 'masterPassword').focus();
document.getElementById(this.pinLock ? "pin" : "masterPassword").focus();
if (this.biometricLock && !disableAutoBiometricsPrompt && this.isInitialLockScreen) {
if (await this.vaultTimeoutService.isLocked()) {
await this.unlockBiometric();
@ -53,15 +75,15 @@ export class LockComponent extends BaseLockComponent {
return;
}
const div = document.createElement('div');
div.innerHTML = `<div class="swal2-text">${this.i18nService.t('awaitDesktop')}</div>`;
const div = document.createElement("div");
div.innerHTML = `<div class="swal2-text">${this.i18nService.t("awaitDesktop")}</div>`;
Swal.fire({
heightAuto: false,
buttonsStyling: false,
html: div,
showCancelButton: true,
cancelButtonText: this.i18nService.t('cancel'),
cancelButtonText: this.i18nService.t("cancel"),
showConfirmButton: false,
});

View File

@ -1,41 +1,57 @@
import { Component, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { Component, NgZone } from "@angular/core";
import { Router } from "@angular/router";
import { AuthService } from 'jslib-common/abstractions/auth.service';
import { CryptoFunctionService } from 'jslib-common/abstractions/cryptoFunction.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StateService } from 'jslib-common/abstractions/state.service';
import { StorageService } from 'jslib-common/abstractions/storage.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { AuthService } from "jslib-common/abstractions/auth.service";
import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StateService } from "jslib-common/abstractions/state.service";
import { StorageService } from "jslib-common/abstractions/storage.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { LoginComponent as BaseLoginComponent } from 'jslib-angular/components/login.component';
import { LoginComponent as BaseLoginComponent } from "jslib-angular/components/login.component";
@Component({
selector: 'app-login',
templateUrl: 'login.component.html',
selector: "app-login",
templateUrl: "login.component.html",
})
export class LoginComponent extends BaseLoginComponent {
constructor(authService: AuthService, router: Router,
protected platformUtilsService: PlatformUtilsService, protected i18nService: I18nService,
protected stateService: StateService, protected environmentService: EnvironmentService,
constructor(
authService: AuthService,
router: Router,
protected platformUtilsService: PlatformUtilsService,
protected i18nService: I18nService,
protected stateService: StateService,
protected environmentService: EnvironmentService,
protected passwordGenerationService: PasswordGenerationService,
protected cryptoFunctionService: CryptoFunctionService, logService: LogService,
syncService: SyncService, ngZone: NgZone) {
super(authService, router, platformUtilsService, i18nService,
stateService, environmentService, passwordGenerationService, cryptoFunctionService,
logService, ngZone);
protected cryptoFunctionService: CryptoFunctionService,
logService: LogService,
syncService: SyncService,
ngZone: NgZone
) {
super(
authService,
router,
platformUtilsService,
i18nService,
stateService,
environmentService,
passwordGenerationService,
cryptoFunctionService,
logService,
ngZone
);
super.onSuccessfulLogin = async () => {
await syncService.fullSync(true);
};
super.successRoute = '/tabs/vault';
super.successRoute = "/tabs/vault";
}
settings() {
this.router.navigate(['environment']);
this.router.navigate(["environment"]);
}
async submit() {

View File

@ -1,36 +1,50 @@
import { Component } from '@angular/core';
import { Component } from "@angular/core";
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { ActivatedRoute, Router } from "@angular/router";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { StateService } from 'jslib-common/abstractions/state.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { StateService } from "jslib-common/abstractions/state.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import {
SetPasswordComponent as BaseSetPasswordComponent,
} from 'jslib-angular/components/set-password.component';
import { SetPasswordComponent as BaseSetPasswordComponent } from "jslib-angular/components/set-password.component";
@Component({
selector: 'app-set-password',
templateUrl: 'set-password.component.html',
selector: "app-set-password",
templateUrl: "set-password.component.html",
})
export class SetPasswordComponent extends BaseSetPasswordComponent {
constructor(apiService: ApiService, i18nService: I18nService,
cryptoService: CryptoService, messagingService: MessagingService,
stateService: StateService, passwordGenerationService: PasswordGenerationService,
platformUtilsService: PlatformUtilsService, policyService: PolicyService, router: Router,
syncService: SyncService, route: ActivatedRoute) {
super(i18nService, cryptoService, messagingService, passwordGenerationService,
platformUtilsService, policyService, router, apiService, syncService, route, stateService);
constructor(
apiService: ApiService,
i18nService: I18nService,
cryptoService: CryptoService,
messagingService: MessagingService,
stateService: StateService,
passwordGenerationService: PasswordGenerationService,
platformUtilsService: PlatformUtilsService,
policyService: PolicyService,
router: Router,
syncService: SyncService,
route: ActivatedRoute
) {
super(
i18nService,
cryptoService,
messagingService,
passwordGenerationService,
platformUtilsService,
policyService,
router,
apiService,
syncService,
route,
stateService
);
}
get masterPasswordScoreWidth() {
@ -40,26 +54,26 @@ export class SetPasswordComponent extends BaseSetPasswordComponent {
get masterPasswordScoreColor() {
switch (this.masterPasswordScore) {
case 4:
return 'success';
return "success";
case 3:
return 'primary';
return "primary";
case 2:
return 'warning';
return "warning";
default:
return 'danger';
return "danger";
}
}
get masterPasswordScoreText() {
switch (this.masterPasswordScore) {
case 4:
return this.i18nService.t('strong');
return this.i18nService.t("strong");
case 3:
return this.i18nService.t('good');
return this.i18nService.t("good");
case 2:
return this.i18nService.t('weak');
return this.i18nService.t("weak");
default:
return this.masterPasswordScore != null ? this.i18nService.t('weak') : null;
return this.masterPasswordScore != null ? this.i18nService.t("weak") : null;
}
}
}

View File

@ -1,44 +1,61 @@
import { Component } from '@angular/core';
import { Component } from "@angular/core";
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { ActivatedRoute, Router } from "@angular/router";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { AuthService } from 'jslib-common/abstractions/auth.service';
import { CryptoFunctionService } from 'jslib-common/abstractions/cryptoFunction.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { AuthService } from "jslib-common/abstractions/auth.service";
import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { SsoComponent as BaseSsoComponent } from 'jslib-angular/components/sso.component';
import { BrowserApi } from '../../browser/browserApi';
import { SsoComponent as BaseSsoComponent } from "jslib-angular/components/sso.component";
import { BrowserApi } from "../../browser/browserApi";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-sso',
templateUrl: 'sso.component.html',
selector: "app-sso",
templateUrl: "sso.component.html",
})
export class SsoComponent extends BaseSsoComponent {
constructor(authService: AuthService, router: Router,
i18nService: I18nService, route: ActivatedRoute, stateService: StateService,
platformUtilsService: PlatformUtilsService, apiService: ApiService,
cryptoFunctionService: CryptoFunctionService, passwordGenerationService: PasswordGenerationService,
syncService: SyncService, environmentService: EnvironmentService, logService: LogService,
private vaultTimeoutService: VaultTimeoutService) {
super(authService, router, i18nService, route, stateService, platformUtilsService,
apiService, cryptoFunctionService, environmentService, passwordGenerationService, logService);
constructor(
authService: AuthService,
router: Router,
i18nService: I18nService,
route: ActivatedRoute,
stateService: StateService,
platformUtilsService: PlatformUtilsService,
apiService: ApiService,
cryptoFunctionService: CryptoFunctionService,
passwordGenerationService: PasswordGenerationService,
syncService: SyncService,
environmentService: EnvironmentService,
logService: LogService,
private vaultTimeoutService: VaultTimeoutService
) {
super(
authService,
router,
i18nService,
route,
stateService,
platformUtilsService,
apiService,
cryptoFunctionService,
environmentService,
passwordGenerationService,
logService
);
const url = this.environmentService.getWebVaultUrl();
this.redirectUri = url + '/sso-connector.html';
this.clientId = 'browser';
this.redirectUri = url + "/sso-connector.html";
this.clientId = "browser";
super.onSuccessfulLogin = async () => {
await syncService.fullSync(true);
@ -47,7 +64,7 @@ export class SsoComponent extends BaseSsoComponent {
BrowserApi.reloadOpenWindows();
}
const thisWindow = window.open('', '_self');
const thisWindow = window.open("", "_self");
thisWindow.close();
};
}

View File

@ -1,65 +1,83 @@
import { ChangeDetectorRef, Component, NgZone } from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { first } from 'rxjs/operators';
import { ChangeDetectorRef, Component, NgZone } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from "rxjs/operators";
import { TwoFactorProviderType } from 'jslib-common/enums/twoFactorProviderType';
import { TwoFactorProviderType } from "jslib-common/enums/twoFactorProviderType";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { AuthService } from 'jslib-common/abstractions/auth.service';
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { AuthService } from "jslib-common/abstractions/auth.service";
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { TwoFactorComponent as BaseTwoFactorComponent } from 'jslib-angular/components/two-factor.component';
import { TwoFactorComponent as BaseTwoFactorComponent } from "jslib-angular/components/two-factor.component";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { StateService } from 'jslib-common/abstractions/state.service';
import { BrowserApi } from '../../browser/browserApi';
import { StateService } from "jslib-common/abstractions/state.service";
import { BrowserApi } from "../../browser/browserApi";
const BroadcasterSubscriptionId = 'TwoFactorComponent';
const BroadcasterSubscriptionId = "TwoFactorComponent";
@Component({
selector: 'app-two-factor',
templateUrl: 'two-factor.component.html',
selector: "app-two-factor",
templateUrl: "two-factor.component.html",
})
export class TwoFactorComponent extends BaseTwoFactorComponent {
showNewWindowMessage = false;
constructor(authService: AuthService, router: Router,
i18nService: I18nService, apiService: ApiService,
platformUtilsService: PlatformUtilsService, private syncService: SyncService,
environmentService: EnvironmentService, private ngZone: NgZone,
private broadcasterService: BroadcasterService, private changeDetectorRef: ChangeDetectorRef,
private popupUtilsService: PopupUtilsService, stateService: StateService, route: ActivatedRoute,
private messagingService: MessagingService, logService: LogService) {
super(authService, router, i18nService, apiService, platformUtilsService, window, environmentService,
stateService, route, logService);
constructor(
authService: AuthService,
router: Router,
i18nService: I18nService,
apiService: ApiService,
platformUtilsService: PlatformUtilsService,
private syncService: SyncService,
environmentService: EnvironmentService,
private ngZone: NgZone,
private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef,
private popupUtilsService: PopupUtilsService,
stateService: StateService,
route: ActivatedRoute,
private messagingService: MessagingService,
logService: LogService
) {
super(
authService,
router,
i18nService,
apiService,
platformUtilsService,
window,
environmentService,
stateService,
route,
logService
);
super.onSuccessfulLogin = () => {
return syncService.fullSync(true);
};
super.successRoute = '/tabs/vault';
this.webAuthnNewTab = this.platformUtilsService.isFirefox() || this.platformUtilsService.isSafari();
super.successRoute = "/tabs/vault";
this.webAuthnNewTab =
this.platformUtilsService.isFirefox() || this.platformUtilsService.isSafari();
}
async ngOnInit() {
if (this.route.snapshot.paramMap.has('webAuthnResponse')) {
if (this.route.snapshot.paramMap.has("webAuthnResponse")) {
// WebAuthn fallback response
this.selectedProviderType = TwoFactorProviderType.WebAuthn;
this.token = this.route.snapshot.paramMap.get('webAuthnResponse');
this.token = this.route.snapshot.paramMap.get("webAuthnResponse");
super.onSuccessfulLogin = async () => {
this.syncService.fullSync(true);
this.messagingService.send('reloadPopup');
this.messagingService.send("reloadPopup");
window.close();
};
this.remember = this.route.snapshot.paramMap.get('remember') === 'true';
this.remember = this.route.snapshot.paramMap.get("remember") === "true";
await this.doSubmit();
return;
}
@ -71,24 +89,30 @@ export class TwoFactorComponent extends BaseTwoFactorComponent {
// WebAuthn prompt appears inside the popup on linux, and requires a larger popup width
// than usual to avoid cutting off the dialog.
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && await this.isLinux()) {
document.body.classList.add('linux-webauthn');
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && (await this.isLinux())) {
document.body.classList.add("linux-webauthn");
}
if (this.selectedProviderType === TwoFactorProviderType.Email &&
this.popupUtilsService.inPopup(window)) {
const confirmed = await this.platformUtilsService.showDialog(this.i18nService.t('popup2faCloseMessage'),
null, this.i18nService.t('yes'), this.i18nService.t('no'));
if (
this.selectedProviderType === TwoFactorProviderType.Email &&
this.popupUtilsService.inPopup(window)
) {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t("popup2faCloseMessage"),
null,
this.i18nService.t("yes"),
this.i18nService.t("no")
);
if (confirmed) {
this.popupUtilsService.popOut(window);
}
}
this.route.queryParams.pipe(first()).subscribe(async qParams => {
if (qParams.sso === 'true') {
this.route.queryParams.pipe(first()).subscribe(async (qParams) => {
if (qParams.sso === "true") {
super.onSuccessfulLogin = () => {
BrowserApi.reloadOpenWindows();
const thisWindow = window.open('', '_self');
const thisWindow = window.open("", "_self");
thisWindow.close();
return this.syncService.fullSync(true);
};
@ -99,17 +123,17 @@ export class TwoFactorComponent extends BaseTwoFactorComponent {
async ngOnDestroy() {
this.broadcasterService.unsubscribe(BroadcasterSubscriptionId);
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && await this.isLinux()) {
document.body.classList.remove('linux-webauthn');
if (this.selectedProviderType === TwoFactorProviderType.WebAuthn && (await this.isLinux())) {
document.body.classList.remove("linux-webauthn");
}
super.ngOnDestroy();
}
anotherMethod() {
this.router.navigate(['2fa-options']);
this.router.navigate(["2fa-options"]);
}
async isLinux() {
return (await BrowserApi.getPlatformInfo()).os === 'linux';
return (await BrowserApi.getPlatformInfo()).os === "linux";
}
}

View File

@ -1,17 +1,17 @@
import { Component } from '@angular/core';
import { Component } from "@angular/core";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { UpdateTempPasswordComponent as BaseUpdateTempPasswordComponent } from 'jslib-angular/components/update-temp-password.component';
import { StateService } from '../../services/abstractions/state.service';
import { UpdateTempPasswordComponent as BaseUpdateTempPasswordComponent } from "jslib-angular/components/update-temp-password.component";
import { StateService } from "../../services/abstractions/state.service";
interface MasterPasswordScore {
Color: string;
@ -20,8 +20,8 @@ interface MasterPasswordScore {
}
@Component({
selector: 'app-update-temp-password',
templateUrl: 'update-temp-password.component.html',
selector: "app-update-temp-password",
templateUrl: "update-temp-password.component.html",
})
export class UpdateTempPasswordComponent extends BaseUpdateTempPasswordComponent {
get masterPasswordScoreStyle(): MasterPasswordScore {
@ -29,38 +29,54 @@ export class UpdateTempPasswordComponent extends BaseUpdateTempPasswordComponent
switch (this.masterPasswordScore) {
case 4:
return {
Color: 'bg-success',
Text: 'strong',
Color: "bg-success",
Text: "strong",
Width: scoreWidth,
};
case 3:
return {
Color: 'bg-primary',
Text: 'good',
Color: "bg-primary",
Text: "good",
Width: scoreWidth,
};
case 2:
return {
Color: 'bg-warning',
Text: 'weak',
Color: "bg-warning",
Text: "weak",
Width: scoreWidth,
};
default:
return {
Color: 'bg-danger',
Text: 'weak',
Color: "bg-danger",
Text: "weak",
Width: scoreWidth,
};
}
}
constructor(i18nService: I18nService, platformUtilsService: PlatformUtilsService,
passwordGenerationService: PasswordGenerationService, policyService: PolicyService,
cryptoService: CryptoService, stateService: StateService,
messagingService: MessagingService, apiService: ApiService,
syncService: SyncService, logService: LogService) {
super(i18nService, platformUtilsService, passwordGenerationService, policyService,
cryptoService, messagingService, apiService, stateService,
syncService, logService);
constructor(
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
passwordGenerationService: PasswordGenerationService,
policyService: PolicyService,
cryptoService: CryptoService,
stateService: StateService,
messagingService: MessagingService,
apiService: ApiService,
syncService: SyncService,
logService: LogService
) {
super(
i18nService,
platformUtilsService,
passwordGenerationService,
policyService,
cryptoService,
messagingService,
apiService,
stateService,
syncService,
logService
);
}
}

View File

@ -1,55 +1,48 @@
import {
ChangeDetectorRef,
Component,
NgZone,
OnInit,
SecurityContext,
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import {
NavigationEnd,
Router,
RouterOutlet,
} from '@angular/router';
import {
IndividualConfig,
ToastrService,
} from 'ngx-toastr';
import Swal, { SweetAlertIcon } from 'sweetalert2/src/sweetalert2.js';
import { BrowserApi } from '../browser/browserApi';
import { ChangeDetectorRef, Component, NgZone, OnInit, SecurityContext } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
import { NavigationEnd, Router, RouterOutlet } from "@angular/router";
import { IndividualConfig, ToastrService } from "ngx-toastr";
import Swal, { SweetAlertIcon } from "sweetalert2/src/sweetalert2.js";
import { BrowserApi } from "../browser/browserApi";
import { AuthService } from 'jslib-common/abstractions/auth.service';
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StorageService } from 'jslib-common/abstractions/storage.service';
import { AuthService } from "jslib-common/abstractions/auth.service";
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StorageService } from "jslib-common/abstractions/storage.service";
import { KeyConnectorService } from 'jslib-common/abstractions/keyConnector.service';
import { routerTransition } from './app-routing.animations';
import { KeyConnectorService } from "jslib-common/abstractions/keyConnector.service";
import { routerTransition } from "./app-routing.animations";
import { StateService } from '../services/abstractions/state.service';
import { StateService } from "../services/abstractions/state.service";
@Component({
selector: 'app-root',
selector: "app-root",
styles: [],
animations: [routerTransition],
template: `
<main [@routerTransition]="getState(o)">
template: ` <main [@routerTransition]="getState(o)">
<router-outlet #o="outlet"></router-outlet>
</main>`,
})
export class AppComponent implements OnInit {
private lastActivity: number = null;
constructor(private toastrService: ToastrService, private storageService: StorageService,
private broadcasterService: BroadcasterService, private authService: AuthService,
private i18nService: I18nService, private router: Router,
private stateService: StateService, private messagingService: MessagingService,
private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone,
private sanitizer: DomSanitizer, private platformUtilsService: PlatformUtilsService,
private keyConnectoService: KeyConnectorService) { }
constructor(
private toastrService: ToastrService,
private storageService: StorageService,
private broadcasterService: BroadcasterService,
private authService: AuthService,
private i18nService: I18nService,
private router: Router,
private stateService: StateService,
private messagingService: MessagingService,
private changeDetectorRef: ChangeDetectorRef,
private ngZone: NgZone,
private sanitizer: DomSanitizer,
private platformUtilsService: PlatformUtilsService,
private keyConnectoService: KeyConnectorService
) {}
ngOnInit() {
if (BrowserApi.getBackgroundPage() == null) {
@ -64,51 +57,57 @@ export class AppComponent implements OnInit {
window.onkeypress = () => this.recordActivity();
});
(window as any).bitwardenPopupMainMessageListener = async (msg: any, sender: any, sendResponse: any) => {
if (msg.command === 'doneLoggingOut') {
(window as any).bitwardenPopupMainMessageListener = async (
msg: any,
sender: any,
sendResponse: any
) => {
if (msg.command === "doneLoggingOut") {
this.ngZone.run(async () => {
this.authService.logOut(async () => {
if (msg.expired) {
this.showToast({
type: 'warning',
title: this.i18nService.t('loggedOut'),
text: this.i18nService.t('loginExpired'),
type: "warning",
title: this.i18nService.t("loggedOut"),
text: this.i18nService.t("loginExpired"),
});
}
await this.stateService.clean();
this.router.navigate(['home']);
this.router.navigate(["home"]);
});
this.changeDetectorRef.detectChanges();
});
} else if (msg.command === 'authBlocked') {
} else if (msg.command === "authBlocked") {
this.ngZone.run(() => {
this.router.navigate(['home']);
this.router.navigate(["home"]);
});
} else if (msg.command === 'locked') {
} else if (msg.command === "locked") {
this.ngZone.run(() => {
this.router.navigate(['lock']);
this.router.navigate(["lock"]);
});
} else if (msg.command === 'showDialog') {
} else if (msg.command === "showDialog") {
await this.showDialog(msg);
} else if (msg.command === 'showToast') {
} else if (msg.command === "showToast") {
this.ngZone.run(() => {
this.showToast(msg);
});
} else if (msg.command === 'reloadProcess') {
const windowReload = this.platformUtilsService.isSafari() ||
this.platformUtilsService.isFirefox() || this.platformUtilsService.isOpera();
} else if (msg.command === "reloadProcess") {
const windowReload =
this.platformUtilsService.isSafari() ||
this.platformUtilsService.isFirefox() ||
this.platformUtilsService.isOpera();
if (windowReload) {
// Wait to make sure background has reloaded first.
window.setTimeout(() => BrowserApi.reloadExtension(window), 2000);
}
} else if (msg.command === 'reloadPopup') {
} else if (msg.command === "reloadPopup") {
this.ngZone.run(() => {
this.router.navigate(['/']);
this.router.navigate(["/"]);
});
} else if (msg.command === 'convertAccountToKeyConnector') {
} else if (msg.command === "convertAccountToKeyConnector") {
this.ngZone.run(async () => {
await this.keyConnectoService.setConvertAccountRequired(true);
this.router.navigate(['/remove-password']);
this.router.navigate(["/remove-password"]);
});
} else {
msg.webExtSender = sender;
@ -116,19 +115,22 @@ export class AppComponent implements OnInit {
}
};
BrowserApi.messageListener('app.component', (window as any).bitwardenPopupMainMessageListener);
BrowserApi.messageListener("app.component", (window as any).bitwardenPopupMainMessageListener);
this.router.events.subscribe(async event => {
this.router.events.subscribe(async (event) => {
if (event instanceof NavigationEnd) {
const url = event.urlAfterRedirects || event.url || '';
if (url.startsWith('/tabs/') && (window as any).previousPopupUrl != null &&
(window as any).previousPopupUrl.startsWith('/tabs/')) {
const url = event.urlAfterRedirects || event.url || "";
if (
url.startsWith("/tabs/") &&
(window as any).previousPopupUrl != null &&
(window as any).previousPopupUrl.startsWith("/tabs/")
) {
await this.stateService.setBrowserGroupingComponentState(null);
await this.stateService.setBrowserCipherComponentState(null);
await this.stateService.setBrowserSendComponentState(null);
await this.stateService.setBrowserSendTypeComponentState(null);
}
if (url.startsWith('/tabs/')) {
if (url.startsWith("/tabs/")) {
await this.stateService.setAddEditCipherInfo(null);
}
(window as any).previousPopupUrl = url;
@ -144,18 +146,24 @@ export class AppComponent implements OnInit {
}
getState(outlet: RouterOutlet) {
if (outlet.activatedRouteData.state === 'ciphers') {
const routeDirection = (window as any).routeDirection != null ? (window as any).routeDirection : '';
return 'ciphers_direction=' + routeDirection + '_' +
(outlet.activatedRoute.queryParams as any).value.folderId + '_' +
(outlet.activatedRoute.queryParams as any).value.collectionId;
if (outlet.activatedRouteData.state === "ciphers") {
const routeDirection =
(window as any).routeDirection != null ? (window as any).routeDirection : "";
return (
"ciphers_direction=" +
routeDirection +
"_" +
(outlet.activatedRoute.queryParams as any).value.folderId +
"_" +
(outlet.activatedRoute.queryParams as any).value.collectionId
);
} else {
return outlet.activatedRouteData.state;
}
}
private async recordActivity() {
const now = (new Date()).getTime();
const now = new Date().getTime();
if (this.lastActivity != null && now - this.lastActivity < 250) {
return;
}
@ -165,17 +173,19 @@ export class AppComponent implements OnInit {
}
private showToast(msg: any) {
let message = '';
let message = "";
const options: Partial<IndividualConfig> = {};
if (typeof (msg.text) === 'string') {
if (typeof msg.text === "string") {
message = msg.text;
} else if (msg.text.length === 1) {
message = msg.text[0];
} else {
msg.text.forEach((t: string) =>
message += ('<p>' + this.sanitizer.sanitize(SecurityContext.HTML, t) + '</p>'));
msg.text.forEach(
(t: string) =>
(message += "<p>" + this.sanitizer.sanitize(SecurityContext.HTML, t) + "</p>")
);
options.enableHtml = true;
}
if (msg.options != null) {
@ -187,7 +197,7 @@ export class AppComponent implements OnInit {
}
}
this.toastrService.show(message, msg.title, options, 'toast-' + msg.type);
this.toastrService.show(message, msg.title, options, "toast-" + msg.type);
}
private async showDialog(msg: any) {
@ -196,17 +206,17 @@ export class AppComponent implements OnInit {
if (type != null) {
// If you add custom types to this part, the type to SweetAlertIcon cast below needs to be changed.
switch (type) {
case 'success':
iconClasses = 'fa-check text-success';
case "success":
iconClasses = "fa-check text-success";
break;
case 'warning':
iconClasses = 'fa-warning text-warning';
case "warning":
iconClasses = "fa-warning text-warning";
break;
case 'error':
iconClasses = 'fa-bolt text-danger';
case "error":
iconClasses = "fa-bolt text-danger";
break;
case 'info':
iconClasses = 'fa-info-circle text-info';
case "info":
iconClasses = "fa-info-circle text-info";
break;
default:
break;
@ -219,18 +229,19 @@ export class AppComponent implements OnInit {
heightAuto: false,
buttonsStyling: false,
icon: type as SweetAlertIcon, // required to be any of the SweetAlertIcons to output the iconHtml.
iconHtml: iconClasses != null ? `<i class="swal-custom-icon fa ${iconClasses}"></i>` : undefined,
iconHtml:
iconClasses != null ? `<i class="swal-custom-icon fa ${iconClasses}"></i>` : undefined,
text: msg.text,
html: msg.html,
titleText: msg.title,
showCancelButton: (cancelText != null),
showCancelButton: cancelText != null,
cancelButtonText: cancelText,
showConfirmButton: true,
confirmButtonText: confirmText == null ? this.i18nService.t('ok') : confirmText,
confirmButtonText: confirmText == null ? this.i18nService.t("ok") : confirmText,
timer: 300000,
});
this.messagingService.send('showDialogResolve', {
this.messagingService.send("showDialogResolve", {
dialogId: msg.dialogId,
confirmed: confirmed.value,
});

View File

@ -1,27 +1,22 @@
import {
Component,
EventEmitter,
Input,
Output,
} from '@angular/core';
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { CipherRepromptType } from 'jslib-common/enums/cipherRepromptType';
import { CipherType } from 'jslib-common/enums/cipherType';
import { EventType } from 'jslib-common/enums/eventType';
import { CipherRepromptType } from "jslib-common/enums/cipherRepromptType";
import { CipherType } from "jslib-common/enums/cipherType";
import { EventType } from "jslib-common/enums/eventType";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CipherView } from "jslib-common/models/view/cipherView";
import { EventService } from 'jslib-common/abstractions/event.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PasswordRepromptService } from 'jslib-common/abstractions/passwordReprompt.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { TotpService } from 'jslib-common/abstractions/totp.service';
import { EventService } from "jslib-common/abstractions/event.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PasswordRepromptService } from "jslib-common/abstractions/passwordReprompt.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { TotpService } from "jslib-common/abstractions/totp.service";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-action-buttons',
templateUrl: 'action-buttons.component.html',
selector: "app-action-buttons",
templateUrl: "action-buttons.component.html",
})
export class ActionButtonsComponent {
@Output() onView = new EventEmitter<CipherView>();
@ -32,10 +27,14 @@ export class ActionButtonsComponent {
cipherType = CipherType;
userHasPremiumAccess = false;
constructor(private i18nService: I18nService,
private platformUtilsService: PlatformUtilsService, private eventService: EventService,
private totpService: TotpService, private stateService: StateService,
private passwordRepromptService: PasswordRepromptService) { }
constructor(
private i18nService: I18nService,
private platformUtilsService: PlatformUtilsService,
private eventService: EventService,
private totpService: TotpService,
private stateService: StateService,
private passwordRepromptService: PasswordRepromptService
) {}
async ngOnInit() {
this.userHasPremiumAccess = await this.stateService.getCanAccessPremium();
@ -46,12 +45,15 @@ export class ActionButtonsComponent {
}
async copy(cipher: CipherView, value: string, typeI18nKey: string, aType: string) {
if (this.cipher.reprompt !== CipherRepromptType.None && this.passwordRepromptService.protectedFields().includes(aType) &&
!await this.passwordRepromptService.showPasswordPrompt()) {
if (
this.cipher.reprompt !== CipherRepromptType.None &&
this.passwordRepromptService.protectedFields().includes(aType) &&
!(await this.passwordRepromptService.showPasswordPrompt())
) {
return;
}
if (value == null || aType === 'TOTP' && !this.displayTotpCopyButton(cipher)) {
if (value == null || (aType === "TOTP" && !this.displayTotpCopyButton(cipher))) {
return;
} else if (value === cipher.login.totp) {
value = await this.totpService.getCode(value);
@ -62,19 +64,23 @@ export class ActionButtonsComponent {
}
this.platformUtilsService.copyToClipboard(value, { window: window });
this.platformUtilsService.showToast('info', null,
this.i18nService.t('valueCopied', this.i18nService.t(typeI18nKey)));
this.platformUtilsService.showToast(
"info",
null,
this.i18nService.t("valueCopied", this.i18nService.t(typeI18nKey))
);
if (typeI18nKey === 'password' || typeI18nKey === 'verificationCodeTotp') {
if (typeI18nKey === "password" || typeI18nKey === "verificationCodeTotp") {
this.eventService.collect(EventType.Cipher_ClientToggledHiddenFieldVisible, cipher.id);
} else if (typeI18nKey === 'securityCode') {
} else if (typeI18nKey === "securityCode") {
this.eventService.collect(EventType.Cipher_ClientCopiedCardCode, cipher.id);
}
}
displayTotpCopyButton(cipher: CipherView) {
return (cipher?.login?.hasTotp ?? false) &&
(cipher.organizationUseTotp || this.userHasPremiumAccess);
return (
(cipher?.login?.hasTotp ?? false) && (cipher.organizationUseTotp || this.userHasPremiumAccess)
);
}
view() {

View File

@ -1,27 +1,29 @@
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { Location } from "@angular/common";
import { Component } from "@angular/core";
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StateService } from '../../services/abstractions/state.service';
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StateService } from "../../services/abstractions/state.service";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CipherView } from "jslib-common/models/view/cipherView";
import {
PasswordGeneratorComponent as BasePasswordGeneratorComponent,
} from 'jslib-angular/components/password-generator.component';
import { PasswordGeneratorComponent as BasePasswordGeneratorComponent } from "jslib-angular/components/password-generator.component";
@Component({
selector: 'app-password-generator',
templateUrl: 'password-generator.component.html',
selector: "app-password-generator",
templateUrl: "password-generator.component.html",
})
export class PasswordGeneratorComponent extends BasePasswordGeneratorComponent {
private cipherState: CipherView;
constructor(passwordGenerationService: PasswordGenerationService, platformUtilsService: PlatformUtilsService,
i18nService: I18nService, private stateService: StateService,
private location: Location) {
constructor(
passwordGenerationService: PasswordGenerationService,
platformUtilsService: PlatformUtilsService,
i18nService: I18nService,
private stateService: StateService,
private location: Location
) {
super(passwordGenerationService, platformUtilsService, i18nService, window);
}

View File

@ -1,34 +1,28 @@
import {
DatePipe,
Location,
} from '@angular/common';
import { DatePipe, Location } from "@angular/common";
import { Component } from '@angular/core';
import { Component } from "@angular/core";
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { SendService } from 'jslib-common/abstractions/send.service';
import { TokenService } from 'jslib-common/abstractions/token.service';
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { SendService } from "jslib-common/abstractions/send.service";
import { TokenService } from "jslib-common/abstractions/token.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { AddEditComponent as BaseAddEditComponent } from 'jslib-angular/components/send/add-edit.component';
import { StateService } from '../../services/abstractions/state.service';
import { AddEditComponent as BaseAddEditComponent } from "jslib-angular/components/send/add-edit.component";
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-send-add-edit',
templateUrl: 'send-add-edit.component.html',
selector: "app-send-add-edit",
templateUrl: "send-add-edit.component.html",
})
export class SendAddEditComponent extends BaseAddEditComponent {
// Options header
@ -40,13 +34,32 @@ export class SendAddEditComponent extends BaseAddEditComponent {
isLinux = false;
isUnsupportedMac = false;
constructor(i18nService: I18nService, platformUtilsService: PlatformUtilsService,
stateService: StateService, messagingService: MessagingService, policyService: PolicyService,
environmentService: EnvironmentService, datePipe: DatePipe, sendService: SendService,
private route: ActivatedRoute, private router: Router, private location: Location,
private popupUtilsService: PopupUtilsService, logService: LogService) {
super(i18nService, platformUtilsService, environmentService, datePipe,
sendService, messagingService, policyService, logService, stateService);
constructor(
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
stateService: StateService,
messagingService: MessagingService,
policyService: PolicyService,
environmentService: EnvironmentService,
datePipe: DatePipe,
sendService: SendService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
private popupUtilsService: PopupUtilsService,
logService: LogService
) {
super(
i18nService,
platformUtilsService,
environmentService,
datePipe,
sendService,
messagingService,
policyService,
logService,
stateService
);
}
get showFileSelector(): boolean {
@ -54,7 +67,10 @@ export class SendAddEditComponent extends BaseAddEditComponent {
}
get showFilePopoutMessage(): boolean {
return !this.editMode && (this.showFirefoxFileWarning || this.showSafariFileWarning || this.showChromiumFileWarning);
return (
!this.editMode &&
(this.showFirefoxFileWarning || this.showSafariFileWarning || this.showChromiumFileWarning)
);
}
get showFirefoxFileWarning(): boolean {
@ -67,7 +83,11 @@ export class SendAddEditComponent extends BaseAddEditComponent {
// Only show this for Chromium based browsers in Linux and Mac > Big Sur
get showChromiumFileWarning(): boolean {
return (this.isLinux || this.isUnsupportedMac) && !this.isFirefox && !(this.inSidebar || this.inPopout);
return (
(this.isLinux || this.isUnsupportedMac) &&
!this.isFirefox &&
!(this.inSidebar || this.inPopout)
);
}
popOutWindow() {
@ -79,10 +99,11 @@ export class SendAddEditComponent extends BaseAddEditComponent {
this.isFirefox = this.platformUtilsService.isFirefox();
this.inPopout = this.popupUtilsService.inPopout(window);
this.inSidebar = this.popupUtilsService.inSidebar(window);
this.isLinux = window?.navigator?.userAgent.indexOf('Linux') !== -1;
this.isUnsupportedMac = this.platformUtilsService.isChrome() && window?.navigator?.appVersion.includes('Mac OS X 11');
this.isLinux = window?.navigator?.userAgent.indexOf("Linux") !== -1;
this.isUnsupportedMac =
this.platformUtilsService.isChrome() && window?.navigator?.appVersion.includes("Mac OS X 11");
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (params.sendId) {
this.sendId = params.sendId;
}
@ -95,7 +116,7 @@ export class SendAddEditComponent extends BaseAddEditComponent {
window.setTimeout(() => {
if (!this.editMode) {
document.getElementById('name').focus();
document.getElementById("name").focus();
}
}, 200);
}
@ -120,8 +141,8 @@ export class SendAddEditComponent extends BaseAddEditComponent {
cancel() {
// If true, the window was pop'd out on the add-send page. location.back will not work
if ((window as any).previousPopupUrl.startsWith('/add-send')) {
this.router.navigate(['tabs/send']);
if ((window as any).previousPopupUrl.startsWith("/add-send")) {
this.router.navigate(["tabs/send"]);
} else {
this.location.back();
}

View File

@ -1,40 +1,34 @@
import {
ChangeDetectorRef,
Component,
NgZone,
} from '@angular/core';
import { ChangeDetectorRef, Component, NgZone } from "@angular/core";
import {
Router,
} from '@angular/router';
import { Router } from "@angular/router";
import { SendView } from 'jslib-common/models/view/sendView';
import { SendView } from "jslib-common/models/view/sendView";
import { SendComponent as BaseSendComponent } from 'jslib-angular/components/send/send.component';
import { SendComponent as BaseSendComponent } from "jslib-angular/components/send/send.component";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { SearchService } from 'jslib-common/abstractions/search.service';
import { SendService } from 'jslib-common/abstractions/send.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { SearchService } from "jslib-common/abstractions/search.service";
import { SendService } from "jslib-common/abstractions/send.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { SendType } from 'jslib-common/enums/sendType';
import { BrowserSendComponentState } from '../../models/browserSendComponentState';
import { SendType } from "jslib-common/enums/sendType";
import { BrowserSendComponentState } from "../../models/browserSendComponentState";
const ComponentId = 'SendComponent';
const ScopeStateId = ComponentId + 'Scope';
const ComponentId = "SendComponent";
const ScopeStateId = ComponentId + "Scope";
@Component({
selector: 'app-send-groupings',
templateUrl: 'send-groupings.component.html',
selector: "app-send-groupings",
templateUrl: "send-groupings.component.html",
})
export class SendGroupingsComponent extends BaseSendComponent {
// Header
@ -45,15 +39,32 @@ export class SendGroupingsComponent extends BaseSendComponent {
state: BrowserSendComponentState;
private loadedTimeout: number;
constructor(sendService: SendService, i18nService: I18nService,
platformUtilsService: PlatformUtilsService, environmentService: EnvironmentService, ngZone: NgZone,
policyService: PolicyService, searchService: SearchService,
private popupUtils: PopupUtilsService, private stateService: StateService,
private router: Router, private syncService: SyncService,
private changeDetectorRef: ChangeDetectorRef, private broadcasterService: BroadcasterService,
logService: LogService) {
super(sendService, i18nService, platformUtilsService, environmentService, ngZone, searchService,
policyService, logService);
constructor(
sendService: SendService,
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
environmentService: EnvironmentService,
ngZone: NgZone,
policyService: PolicyService,
searchService: SearchService,
private popupUtils: PopupUtilsService,
private stateService: StateService,
private router: Router,
private syncService: SyncService,
private changeDetectorRef: ChangeDetectorRef,
private broadcasterService: BroadcasterService,
logService: LogService
) {
super(
sendService,
i18nService,
platformUtilsService,
environmentService,
ngZone,
searchService,
policyService,
logService
);
super.onSuccessfulLoad = async () => {
this.calculateTypeCounts();
this.selectAll();
@ -62,7 +73,9 @@ export class SendGroupingsComponent extends BaseSendComponent {
async ngOnInit() {
// Determine Header details
this.showLeftHeader = !(this.popupUtils.inSidebar(window) && this.platformUtilsService.isFirefox());
this.showLeftHeader = !(
this.popupUtils.inSidebar(window) && this.platformUtilsService.isFirefox()
);
// Clear state of Send Type Component
this.stateService.setBrowserSendComponentState(null);
// Let super class finish
@ -91,7 +104,7 @@ export class SendGroupingsComponent extends BaseSendComponent {
this.broadcasterService.subscribe(ComponentId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'syncCompleted':
case "syncCompleted":
window.setTimeout(() => {
this.load();
}, 500);
@ -117,18 +130,18 @@ export class SendGroupingsComponent extends BaseSendComponent {
}
async selectType(type: SendType) {
this.router.navigate(['/send-type'], { queryParams: { type: type } });
this.router.navigate(["/send-type"], { queryParams: { type: type } });
}
async selectSend(s: SendView) {
this.router.navigate(['/edit-send'], { queryParams: { sendId: s.id } });
this.router.navigate(["/edit-send"], { queryParams: { sendId: s.id } });
}
async addSend() {
if (this.disableSend) {
return;
}
this.router.navigate(['/add-send']);
this.router.navigate(["/add-send"]);
}
async removePassword(s: SendView): Promise<boolean> {
@ -139,13 +152,15 @@ export class SendGroupingsComponent extends BaseSendComponent {
}
showSearching() {
return this.hasSearched || (!this.searchPending && this.searchService.isSearchable(this.searchText));
return (
this.hasSearched || (!this.searchPending && this.searchService.isSearchable(this.searchText))
);
}
private calculateTypeCounts() {
// Create type counts
const typeCounts = new Map<SendType, number>();
this.sends.forEach(s => {
this.sends.forEach((s) => {
if (typeCounts.has(s.type)) {
typeCounts.set(s.type, typeCounts.get(s.type) + 1);
} else {

View File

@ -1,42 +1,35 @@
import {
ChangeDetectorRef,
Component,
NgZone,
} from '@angular/core';
import { ChangeDetectorRef, Component, NgZone } from "@angular/core";
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { Location } from '@angular/common';
import { Location } from "@angular/common";
import { SendView } from 'jslib-common/models/view/sendView';
import { SendView } from "jslib-common/models/view/sendView";
import { SendComponent as BaseSendComponent } from 'jslib-angular/components/send/send.component';
import { SendComponent as BaseSendComponent } from "jslib-angular/components/send/send.component";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { SearchService } from 'jslib-common/abstractions/search.service';
import { SendService } from 'jslib-common/abstractions/send.service';
import { StateService } from '../../services/abstractions/state.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { SearchService } from "jslib-common/abstractions/search.service";
import { SendService } from "jslib-common/abstractions/send.service";
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { SendType } from 'jslib-common/enums/sendType';
import { BrowserComponentState } from '../../models/browserComponentState';
import { SendType } from "jslib-common/enums/sendType";
import { BrowserComponentState } from "../../models/browserComponentState";
const ComponentId = 'SendTypeComponent';
const ComponentId = "SendTypeComponent";
@Component({
selector: 'app-send-type',
templateUrl: 'send-type.component.html',
selector: "app-send-type",
templateUrl: "send-type.component.html",
})
export class SendTypeComponent extends BaseSendComponent {
groupingTitle: string;
@ -45,27 +38,47 @@ export class SendTypeComponent extends BaseSendComponent {
private refreshTimeout: number;
private applySavedState = true;
constructor(sendService: SendService, i18nService: I18nService,
platformUtilsService: PlatformUtilsService, environmentService: EnvironmentService, ngZone: NgZone,
policyService: PolicyService, searchService: SearchService,
private popupUtils: PopupUtilsService, private stateService: StateService,
private route: ActivatedRoute, private location: Location, private changeDetectorRef: ChangeDetectorRef,
private broadcasterService: BroadcasterService, private router: Router, logService: LogService) {
super(sendService, i18nService, platformUtilsService, environmentService, ngZone, searchService,
policyService, logService);
constructor(
sendService: SendService,
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
environmentService: EnvironmentService,
ngZone: NgZone,
policyService: PolicyService,
searchService: SearchService,
private popupUtils: PopupUtilsService,
private stateService: StateService,
private route: ActivatedRoute,
private location: Location,
private changeDetectorRef: ChangeDetectorRef,
private broadcasterService: BroadcasterService,
private router: Router,
logService: LogService
) {
super(
sendService,
i18nService,
platformUtilsService,
environmentService,
ngZone,
searchService,
policyService,
logService
);
super.onSuccessfulLoad = async () => {
this.selectType(this.type);
};
this.applySavedState = (window as any).previousPopupUrl != null &&
!(window as any).previousPopupUrl.startsWith('/send-type');
this.applySavedState =
(window as any).previousPopupUrl != null &&
!(window as any).previousPopupUrl.startsWith("/send-type");
}
async ngOnInit() {
// Let super class finish
await super.ngOnInit();
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (this.applySavedState) {
this.state = (await this.stateService.getBrowserSendTypeComponentState());
this.state = await this.stateService.getBrowserSendTypeComponentState();
if (this.state.searchText != null) {
this.searchText = this.state.searchText;
}
@ -75,15 +88,15 @@ export class SendTypeComponent extends BaseSendComponent {
this.type = parseInt(params.type, null);
switch (this.type) {
case SendType.Text:
this.groupingTitle = this.i18nService.t('sendTypeText');
this.groupingTitle = this.i18nService.t("sendTypeText");
break;
case SendType.File:
this.groupingTitle = this.i18nService.t('sendTypeFile');
this.groupingTitle = this.i18nService.t("sendTypeFile");
break;
default:
break;
}
await this.load(s => s.type === this.type);
await this.load((s) => s.type === this.type);
}
// Restore state and remove reference
@ -91,14 +104,13 @@ export class SendTypeComponent extends BaseSendComponent {
window.setTimeout(() => this.popupUtils.setContentScrollY(window, this.state?.scrollY), 0);
}
this.stateService.setBrowserSendComponentState(null);
});
// Refresh Send list if sync completed in background
this.broadcasterService.subscribe(ComponentId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'syncCompleted':
case "syncCompleted":
if (message.successfully) {
this.refreshTimeout = window.setTimeout(() => {
this.refresh();
@ -126,14 +138,14 @@ export class SendTypeComponent extends BaseSendComponent {
}
async selectSend(s: SendView) {
this.router.navigate(['/edit-send'], { queryParams: { sendId: s.id } });
this.router.navigate(["/edit-send"], { queryParams: { sendId: s.id } });
}
async addSend() {
if (this.disableSend) {
return;
}
this.router.navigate(['/add-send'], { queryParams: { type: this.type } });
this.router.navigate(["/add-send"], { queryParams: { type: this.type } });
}
async removePassword(s: SendView): Promise<boolean> {
@ -144,7 +156,7 @@ export class SendTypeComponent extends BaseSendComponent {
}
back() {
(window as any).routeDirection = 'b';
(window as any).routeDirection = "b";
this.location.back();
}

View File

@ -1,129 +1,131 @@
import {
APP_INITIALIZER,
LOCALE_ID,
NgModule,
} from '@angular/core';
import { APP_INITIALIZER, LOCALE_ID, NgModule } from "@angular/core";
import { DebounceNavigationService } from './debounceNavigationService';
import { LaunchGuardService } from './launch-guard.service';
import { LockGuardService } from './lock-guard.service';
import { PasswordRepromptService } from './password-reprompt.service';
import { UnauthGuardService } from './unauth-guard.service';
import { DebounceNavigationService } from "./debounceNavigationService";
import { LaunchGuardService } from "./launch-guard.service";
import { LockGuardService } from "./lock-guard.service";
import { PasswordRepromptService } from "./password-reprompt.service";
import { UnauthGuardService } from "./unauth-guard.service";
import { JslibServicesModule } from 'jslib-angular/services/jslib-services.module';
import { LockGuardService as BaseLockGuardService } from 'jslib-angular/services/lock-guard.service';
import { UnauthGuardService as BaseUnauthGuardService } from 'jslib-angular/services/unauth-guard.service';
import { JslibServicesModule } from "jslib-angular/services/jslib-services.module";
import { LockGuardService as BaseLockGuardService } from "jslib-angular/services/lock-guard.service";
import { UnauthGuardService as BaseUnauthGuardService } from "jslib-angular/services/unauth-guard.service";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { AppIdService } from 'jslib-common/abstractions/appId.service';
import { AuditService } from 'jslib-common/abstractions/audit.service';
import { AuthService as AuthServiceAbstraction } from 'jslib-common/abstractions/auth.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { CryptoFunctionService } from 'jslib-common/abstractions/cryptoFunction.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { EventService } from 'jslib-common/abstractions/event.service';
import { ExportService } from 'jslib-common/abstractions/export.service';
import { FileUploadService } from 'jslib-common/abstractions/fileUpload.service';
import { FolderService } from 'jslib-common/abstractions/folder.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { KeyConnectorService } from 'jslib-common/abstractions/keyConnector.service';
import { LogService as LogServiceAbstraction } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { NotificationsService } from 'jslib-common/abstractions/notifications.service';
import { OrganizationService } from 'jslib-common/abstractions/organization.service';
import { PasswordGenerationService } from 'jslib-common/abstractions/passwordGeneration.service';
import { PasswordRepromptService as PasswordRepromptServiceAbstraction } from 'jslib-common/abstractions/passwordReprompt.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { ProviderService } from 'jslib-common/abstractions/provider.service';
import { SearchService as SearchServiceAbstraction } from 'jslib-common/abstractions/search.service';
import { SendService } from 'jslib-common/abstractions/send.service';
import { SettingsService } from 'jslib-common/abstractions/settings.service';
import { StorageService } from 'jslib-common/abstractions/storage.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { TokenService } from 'jslib-common/abstractions/token.service';
import { TotpService } from 'jslib-common/abstractions/totp.service';
import { UserVerificationService } from 'jslib-common/abstractions/userVerification.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { AppIdService } from "jslib-common/abstractions/appId.service";
import { AuditService } from "jslib-common/abstractions/audit.service";
import { AuthService as AuthServiceAbstraction } from "jslib-common/abstractions/auth.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { EventService } from "jslib-common/abstractions/event.service";
import { ExportService } from "jslib-common/abstractions/export.service";
import { FileUploadService } from "jslib-common/abstractions/fileUpload.service";
import { FolderService } from "jslib-common/abstractions/folder.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { KeyConnectorService } from "jslib-common/abstractions/keyConnector.service";
import { LogService as LogServiceAbstraction } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { NotificationsService } from "jslib-common/abstractions/notifications.service";
import { OrganizationService } from "jslib-common/abstractions/organization.service";
import { PasswordGenerationService } from "jslib-common/abstractions/passwordGeneration.service";
import { PasswordRepromptService as PasswordRepromptServiceAbstraction } from "jslib-common/abstractions/passwordReprompt.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { ProviderService } from "jslib-common/abstractions/provider.service";
import { SearchService as SearchServiceAbstraction } from "jslib-common/abstractions/search.service";
import { SendService } from "jslib-common/abstractions/send.service";
import { SettingsService } from "jslib-common/abstractions/settings.service";
import { StorageService } from "jslib-common/abstractions/storage.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { TokenService } from "jslib-common/abstractions/token.service";
import { TotpService } from "jslib-common/abstractions/totp.service";
import { UserVerificationService } from "jslib-common/abstractions/userVerification.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { AutofillService } from '../../services/abstractions/autofill.service';
import BrowserMessagingService from '../../services/browserMessaging.service';
import { AutofillService } from "../../services/abstractions/autofill.service";
import BrowserMessagingService from "../../services/browserMessaging.service";
import { AuthService } from 'jslib-common/services/auth.service';
import { ConsoleLogService } from 'jslib-common/services/consoleLog.service';
import { SearchService } from 'jslib-common/services/search.service';
import { AuthService } from "jslib-common/services/auth.service";
import { ConsoleLogService } from "jslib-common/services/consoleLog.service";
import { SearchService } from "jslib-common/services/search.service";
import { PopupSearchService } from './popup-search.service';
import { PopupUtilsService } from './popup-utils.service';
import { PopupSearchService } from "./popup-search.service";
import { PopupUtilsService } from "./popup-utils.service";
import { ThemeType } from 'jslib-common/enums/themeType';
import { StateService } from '../../services/state.service';
import { ThemeType } from "jslib-common/enums/themeType";
import { StateService } from "../../services/state.service";
import { StateService as StateServiceAbstraction } from '../../services/abstractions/state.service';
import { StateService as StateServiceAbstraction } from "../../services/abstractions/state.service";
function getBgService<T>(service: string) {
return (): T => {
const page = BrowserApi.getBackgroundPage();
return page ? page.bitwardenMain[service] as T : null;
return page ? (page.bitwardenMain[service] as T) : null;
};
}
const isPrivateMode = BrowserApi.getBackgroundPage() == null;
export function initFactory(platformUtilsService: PlatformUtilsService, i18nService: I18nService,
storageService: StorageService, popupUtilsService: PopupUtilsService, stateService: StateServiceAbstraction,
logService: LogServiceAbstraction): Function {
export function initFactory(
platformUtilsService: PlatformUtilsService,
i18nService: I18nService,
storageService: StorageService,
popupUtilsService: PopupUtilsService,
stateService: StateServiceAbstraction,
logService: LogServiceAbstraction
): Function {
return async () => {
if (!popupUtilsService.inPopup(window)) {
window.document.body.classList.add('body-full');
window.document.body.classList.add("body-full");
} else if (window.screen.availHeight < 600) {
window.document.body.classList.add('body-xs');
window.document.body.classList.add("body-xs");
} else if (window.screen.availHeight <= 800) {
window.document.body.classList.add('body-sm');
window.document.body.classList.add("body-sm");
}
if (!isPrivateMode) {
const htmlEl = window.document.documentElement;
const theme = await platformUtilsService.getEffectiveTheme();
htmlEl.classList.add('theme_' + theme);
platformUtilsService.onDefaultSystemThemeChange(async sysTheme => {
htmlEl.classList.add("theme_" + theme);
platformUtilsService.onDefaultSystemThemeChange(async (sysTheme) => {
const bwTheme = await stateService.getTheme();
if (bwTheme == null || bwTheme === ThemeType.System) {
htmlEl.classList.remove('theme_' + ThemeType.Light, 'theme_' + ThemeType.Dark);
htmlEl.classList.add('theme_' + sysTheme);
htmlEl.classList.remove("theme_" + ThemeType.Light, "theme_" + ThemeType.Dark);
htmlEl.classList.add("theme_" + sysTheme);
}
});
htmlEl.classList.add('locale_' + i18nService.translationLocale);
htmlEl.classList.add("locale_" + i18nService.translationLocale);
// Workaround for slow performance on external monitors on Chrome + MacOS
// See: https://bugs.chromium.org/p/chromium/issues/detail?id=971701#c64
if (platformUtilsService.isChrome() &&
navigator.platform.indexOf('Mac') > -1 &&
if (
platformUtilsService.isChrome() &&
navigator.platform.indexOf("Mac") > -1 &&
popupUtilsService.inPopup(window) &&
(window.screenLeft < 0 ||
window.screenTop < 0 ||
window.screenLeft > window.screen.width ||
window.screenTop > window.screen.height)) {
htmlEl.classList.add('force_redraw');
logService.info('Force redraw is on');
window.screenTop > window.screen.height)
) {
htmlEl.classList.add("force_redraw");
logService.info("Force redraw is on");
}
}
};
}
@NgModule({
imports: [
JslibServicesModule,
],
imports: [JslibServicesModule],
declarations: [],
providers: [
{
provide: LOCALE_ID,
useFactory: () => isPrivateMode ? null : getBgService<I18nService>('i18nService')().translationLocale,
useFactory: () =>
isPrivateMode ? null : getBgService<I18nService>("i18nService")().translationLocale,
deps: [],
},
{
@ -145,79 +147,136 @@ export function initFactory(platformUtilsService: PlatformUtilsService, i18nServ
DebounceNavigationService,
PopupUtilsService,
{ provide: MessagingService, useClass: BrowserMessagingService },
{ provide: AuthServiceAbstraction, useFactory: getBgService<AuthService>('authService'), deps: [] },
{ provide: StateServiceAbstraction, useFactory: getBgService<StateService>('stateService') },
{
provide: SearchServiceAbstraction,
useFactory: (cipherService: CipherService, logService: ConsoleLogService, i18nService: I18nService) => {
return isPrivateMode ? null : new PopupSearchService(getBgService<SearchService>('searchService')(),
cipherService, logService, i18nService);
},
deps: [
CipherService,
LogServiceAbstraction,
I18nService,
],
},
{ provide: AuditService, useFactory: getBgService<AuditService>('auditService'), deps: [] },
{ provide: FileUploadService, useFactory: getBgService<FileUploadService>('fileUploadService'), deps: [] },
{ provide: CipherService, useFactory: getBgService<CipherService>('cipherService'), deps: [] },
{
provide: CryptoFunctionService,
useFactory: getBgService<CryptoFunctionService>('cryptoFunctionService'),
provide: AuthServiceAbstraction,
useFactory: getBgService<AuthService>("authService"),
deps: [],
},
{ provide: FolderService, useFactory: getBgService<FolderService>('folderService'), deps: [] },
{ provide: CollectionService, useFactory: getBgService<CollectionService>('collectionService'), deps: [] },
{ provide: LogServiceAbstraction, useFactory: getBgService<ConsoleLogService>('logService'), deps: [] },
{ provide: EnvironmentService, useFactory: getBgService<EnvironmentService>('environmentService'), deps: [] },
{ provide: TotpService, useFactory: getBgService<TotpService>('totpService'), deps: [] },
{ provide: TokenService, useFactory: getBgService<TokenService>('tokenService'), deps: [] },
{ provide: I18nService, useFactory: getBgService<I18nService>('i18nService'), deps: [] },
{ provide: CryptoService, useFactory: getBgService<CryptoService>('cryptoService'), deps: [] },
{ provide: EventService, useFactory: getBgService<EventService>('eventService'), deps: [] },
{ provide: PolicyService, useFactory: getBgService<PolicyService>('policyService'), deps: [] },
{ provide: StateServiceAbstraction, useFactory: getBgService<StateService>("stateService") },
{
provide: SearchServiceAbstraction,
useFactory: (
cipherService: CipherService,
logService: ConsoleLogService,
i18nService: I18nService
) => {
return isPrivateMode
? null
: new PopupSearchService(
getBgService<SearchService>("searchService")(),
cipherService,
logService,
i18nService
);
},
deps: [CipherService, LogServiceAbstraction, I18nService],
},
{ provide: AuditService, useFactory: getBgService<AuditService>("auditService"), deps: [] },
{
provide: FileUploadService,
useFactory: getBgService<FileUploadService>("fileUploadService"),
deps: [],
},
{ provide: CipherService, useFactory: getBgService<CipherService>("cipherService"), deps: [] },
{
provide: CryptoFunctionService,
useFactory: getBgService<CryptoFunctionService>("cryptoFunctionService"),
deps: [],
},
{ provide: FolderService, useFactory: getBgService<FolderService>("folderService"), deps: [] },
{
provide: CollectionService,
useFactory: getBgService<CollectionService>("collectionService"),
deps: [],
},
{
provide: LogServiceAbstraction,
useFactory: getBgService<ConsoleLogService>("logService"),
deps: [],
},
{
provide: EnvironmentService,
useFactory: getBgService<EnvironmentService>("environmentService"),
deps: [],
},
{ provide: TotpService, useFactory: getBgService<TotpService>("totpService"), deps: [] },
{ provide: TokenService, useFactory: getBgService<TokenService>("tokenService"), deps: [] },
{ provide: I18nService, useFactory: getBgService<I18nService>("i18nService"), deps: [] },
{ provide: CryptoService, useFactory: getBgService<CryptoService>("cryptoService"), deps: [] },
{ provide: EventService, useFactory: getBgService<EventService>("eventService"), deps: [] },
{ provide: PolicyService, useFactory: getBgService<PolicyService>("policyService"), deps: [] },
{
provide: PlatformUtilsService,
useFactory: getBgService<PlatformUtilsService>('platformUtilsService'),
useFactory: getBgService<PlatformUtilsService>("platformUtilsService"),
deps: [],
},
{
provide: PasswordGenerationService,
useFactory: getBgService<PasswordGenerationService>('passwordGenerationService'),
useFactory: getBgService<PasswordGenerationService>("passwordGenerationService"),
deps: [],
},
{ provide: ApiService, useFactory: getBgService<ApiService>("apiService"), deps: [] },
{ provide: SyncService, useFactory: getBgService<SyncService>("syncService"), deps: [] },
{
provide: SettingsService,
useFactory: getBgService<SettingsService>("settingsService"),
deps: [],
},
{
provide: StorageService,
useFactory: getBgService<StorageService>("storageService"),
deps: [],
},
{ provide: AppIdService, useFactory: getBgService<AppIdService>("appIdService"), deps: [] },
{
provide: AutofillService,
useFactory: getBgService<AutofillService>("autofillService"),
deps: [],
},
{ provide: ExportService, useFactory: getBgService<ExportService>("exportService"), deps: [] },
{ provide: SendService, useFactory: getBgService<SendService>("sendService"), deps: [] },
{
provide: KeyConnectorService,
useFactory: getBgService<KeyConnectorService>("keyConnectorService"),
deps: [],
},
{ provide: ApiService, useFactory: getBgService<ApiService>('apiService'), deps: [] },
{ provide: SyncService, useFactory: getBgService<SyncService>('syncService'), deps: [] },
{ provide: SettingsService, useFactory: getBgService<SettingsService>('settingsService'), deps: [] },
{ provide: StorageService, useFactory: getBgService<StorageService>('storageService'), deps: [] },
{ provide: AppIdService, useFactory: getBgService<AppIdService>('appIdService'), deps: [] },
{ provide: AutofillService, useFactory: getBgService<AutofillService>('autofillService'), deps: [] },
{ provide: ExportService, useFactory: getBgService<ExportService>('exportService'), deps: [] },
{ provide: SendService, useFactory: getBgService<SendService>('sendService'), deps: [] },
{ provide: KeyConnectorService, useFactory: getBgService<KeyConnectorService>('keyConnectorService'), deps: [] },
{
provide: UserVerificationService,
useFactory: getBgService<UserVerificationService>('userVerificationService'),
useFactory: getBgService<UserVerificationService>("userVerificationService"),
deps: [],
},
{
provide: VaultTimeoutService,
useFactory: getBgService<VaultTimeoutService>('vaultTimeoutService'),
useFactory: getBgService<VaultTimeoutService>("vaultTimeoutService"),
deps: [],
},
{
provide: NotificationsService,
useFactory: getBgService<NotificationsService>('notificationsService'),
useFactory: getBgService<NotificationsService>("notificationsService"),
deps: [],
},
{
provide: LogServiceAbstraction,
useFactory: getBgService<ConsoleLogService>("logService"),
deps: [],
},
{ provide: LogServiceAbstraction, useFactory: getBgService<ConsoleLogService>('logService'), deps: [] },
{ provide: PasswordRepromptServiceAbstraction, useClass: PasswordRepromptService },
{ provide: PasswordRepromptServiceAbstraction, useClass: PasswordRepromptService },
{ provide: OrganizationService, useFactory: getBgService<OrganizationService>('organizationService'), deps: [] },
{ provide: ProviderService, useFactory: getBgService<ProviderService>('providerService'), deps: [] },
{ provide: 'SECURE_STORAGE', useFactory: getBgService<StorageService>('secureStorageService'), deps: [] },
{
provide: OrganizationService,
useFactory: getBgService<OrganizationService>("organizationService"),
deps: [],
},
{
provide: ProviderService,
useFactory: getBgService<ProviderService>("providerService"),
deps: [],
},
{
provide: "SECURE_STORAGE",
useFactory: getBgService<StorageService>("secureStorageService"),
deps: [],
},
],
})
export class ServicesModule {
}
export class ServicesModule {}

View File

@ -1,43 +1,41 @@
import {
Component,
NgZone,
OnDestroy,
OnInit,
} from '@angular/core';
import { Component, NgZone, OnDestroy, OnInit } from "@angular/core";
import { Router } from '@angular/router';
import { Router } from "@angular/router";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
import { Utils } from 'jslib-common/misc/utils';
import { Utils } from "jslib-common/misc/utils";
interface ExcludedDomain {
uri: string;
showCurrentUris: boolean;
}
const BroadcasterSubscriptionId = 'excludedDomains';
const BroadcasterSubscriptionId = "excludedDomains";
@Component({
selector: 'app-excluded-domains',
templateUrl: 'excluded-domains.component.html',
selector: "app-excluded-domains",
templateUrl: "excluded-domains.component.html",
})
export class ExcludedDomainsComponent implements OnInit, OnDestroy {
excludedDomains: ExcludedDomain[] = [];
currentUris: string[];
loadCurrentUrisTimeout: number;
constructor(private stateService: StateService,
private i18nService: I18nService, private router: Router,
private broadcasterService: BroadcasterService, private ngZone: NgZone,
private platformUtilsService: PlatformUtilsService) {
}
constructor(
private stateService: StateService,
private i18nService: I18nService,
private router: Router,
private broadcasterService: BroadcasterService,
private ngZone: NgZone,
private platformUtilsService: PlatformUtilsService
) {}
async ngOnInit() {
const savedDomains = await this.stateService.getNeverDomains();
@ -52,12 +50,15 @@ export class ExcludedDomainsComponent implements OnInit, OnDestroy {
this.broadcasterService.subscribe(BroadcasterSubscriptionId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'tabChanged':
case 'windowChanged':
case "tabChanged":
case "windowChanged":
if (this.loadCurrentUrisTimeout != null) {
window.clearTimeout(this.loadCurrentUrisTimeout);
}
this.loadCurrentUrisTimeout = window.setTimeout(async () => await this.loadCurrentUris(), 500);
this.loadCurrentUrisTimeout = window.setTimeout(
async () => await this.loadCurrentUris(),
500
);
break;
default:
break;
@ -71,7 +72,7 @@ export class ExcludedDomainsComponent implements OnInit, OnDestroy {
}
async addUri() {
this.excludedDomains.push({ uri: '', showCurrentUris: false });
this.excludedDomains.push({ uri: "", showCurrentUris: false });
}
async removeUri(i: number) {
@ -81,18 +82,21 @@ export class ExcludedDomainsComponent implements OnInit, OnDestroy {
async submit() {
const savedDomains: { [name: string]: null } = {};
for (const domain of this.excludedDomains) {
if (domain.uri && domain.uri !== '') {
if (domain.uri && domain.uri !== "") {
const validDomain = Utils.getHostname(domain.uri);
if (!validDomain) {
this.platformUtilsService.showToast('error', null,
this.i18nService.t('excludedDomainsInvalidDomain', domain.uri));
this.platformUtilsService.showToast(
"error",
null,
this.i18nService.t("excludedDomainsInvalidDomain", domain.uri)
);
return;
}
savedDomains[validDomain] = null;
}
}
await this.stateService.setNeverDomains(savedDomains);
this.router.navigate(['/tabs/settings']);
this.router.navigate(["/tabs/settings"]);
}
trackByFunction(index: number, item: any) {
@ -104,9 +108,9 @@ export class ExcludedDomainsComponent implements OnInit, OnDestroy {
}
async loadCurrentUris() {
const tabs = await BrowserApi.tabsQuery({ windowType: 'normal' });
const tabs = await BrowserApi.tabsQuery({ windowType: "normal" });
if (tabs) {
const uriSet = new Set(tabs.map(tab => Utils.getHostname(tab.url)));
const uriSet = new Set(tabs.map((tab) => Utils.getHostname(tab.url)));
uriSet.delete(null);
this.currentUris = Array.from(uriSet);
}

View File

@ -1,20 +1,17 @@
import {
Component,
OnInit,
} from '@angular/core';
import { Component, OnInit } from "@angular/core";
import { ThemeType } from 'jslib-common/enums/themeType';
import { UriMatchType } from 'jslib-common/enums/uriMatchType';
import { ThemeType } from "jslib-common/enums/themeType";
import { UriMatchType } from "jslib-common/enums/uriMatchType";
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { TotpService } from 'jslib-common/abstractions/totp.service';
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { TotpService } from "jslib-common/abstractions/totp.service";
import { StateService } from '../../services/abstractions/state.service';
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-options',
templateUrl: 'options.component.html',
selector: "app-options",
templateUrl: "options.component.html",
})
export class OptionsComponent implements OnInit {
disableFavicon = false;
@ -39,46 +36,52 @@ export class OptionsComponent implements OnInit {
showAutofill: boolean = true;
showDisplay: boolean = true;
constructor(private messagingService: MessagingService, private stateService: StateService,
private totpService: TotpService, i18nService: I18nService) {
constructor(
private messagingService: MessagingService,
private stateService: StateService,
private totpService: TotpService,
i18nService: I18nService
) {
this.themeOptions = [
{ name: i18nService.t('default'), value: null },
{ name: i18nService.t('light'), value: ThemeType.Light },
{ name: i18nService.t('dark'), value: ThemeType.Dark },
{ name: 'Nord', value: ThemeType.Nord },
{ name: i18nService.t('solarizedDark'), value: ThemeType.SolarizedDark },
{ name: i18nService.t("default"), value: null },
{ name: i18nService.t("light"), value: ThemeType.Light },
{ name: i18nService.t("dark"), value: ThemeType.Dark },
{ name: "Nord", value: ThemeType.Nord },
{ name: i18nService.t("solarizedDark"), value: ThemeType.SolarizedDark },
];
this.uriMatchOptions = [
{ name: i18nService.t('baseDomain'), value: UriMatchType.Domain },
{ name: i18nService.t('host'), value: UriMatchType.Host },
{ name: i18nService.t('startsWith'), value: UriMatchType.StartsWith },
{ name: i18nService.t('regEx'), value: UriMatchType.RegularExpression },
{ name: i18nService.t('exact'), value: UriMatchType.Exact },
{ name: i18nService.t('never'), value: UriMatchType.Never },
{ name: i18nService.t("baseDomain"), value: UriMatchType.Domain },
{ name: i18nService.t("host"), value: UriMatchType.Host },
{ name: i18nService.t("startsWith"), value: UriMatchType.StartsWith },
{ name: i18nService.t("regEx"), value: UriMatchType.RegularExpression },
{ name: i18nService.t("exact"), value: UriMatchType.Exact },
{ name: i18nService.t("never"), value: UriMatchType.Never },
];
this.clearClipboardOptions = [
{ name: i18nService.t('never'), value: null },
{ name: i18nService.t('tenSeconds'), value: 10 },
{ name: i18nService.t('twentySeconds'), value: 20 },
{ name: i18nService.t('thirtySeconds'), value: 30 },
{ name: i18nService.t('oneMinute'), value: 60 },
{ name: i18nService.t('twoMinutes'), value: 120 },
{ name: i18nService.t('fiveMinutes'), value: 300 },
{ name: i18nService.t("never"), value: null },
{ name: i18nService.t("tenSeconds"), value: 10 },
{ name: i18nService.t("twentySeconds"), value: 20 },
{ name: i18nService.t("thirtySeconds"), value: 30 },
{ name: i18nService.t("oneMinute"), value: 60 },
{ name: i18nService.t("twoMinutes"), value: 120 },
{ name: i18nService.t("fiveMinutes"), value: 300 },
];
this.autoFillOnPageLoadOptions = [
{ name: i18nService.t('autoFillOnPageLoadYes'), value: true },
{ name: i18nService.t('autoFillOnPageLoadNo'), value: false },
{ name: i18nService.t("autoFillOnPageLoadYes"), value: true },
{ name: i18nService.t("autoFillOnPageLoadNo"), value: false },
];
}
async ngOnInit() {
this.enableAutoFillOnPageLoad = await this.stateService.getEnableAutoFillOnPageLoad();
this.autoFillOnPageLoadDefault = await this.stateService.getAutoFillOnPageLoadDefault() ?? true;
this.autoFillOnPageLoadDefault =
(await this.stateService.getAutoFillOnPageLoadDefault()) ?? true;
this.disableAddLoginNotification = await this.stateService.getDisableAddLoginNotification();
this.disableChangedPasswordNotification = await this.stateService.getDisableChangedPasswordNotification();
this.disableChangedPasswordNotification =
await this.stateService.getDisableChangedPasswordNotification();
this.disableContextMenuItem = await this.stateService.getDisableContextMenuItem();
@ -104,12 +107,14 @@ export class OptionsComponent implements OnInit {
}
async updateChangedPasswordNotification() {
await this.stateService.setDisableChangedPasswordNotification(this.disableChangedPasswordNotification);
await this.stateService.setDisableChangedPasswordNotification(
this.disableChangedPasswordNotification
);
}
async updateDisableContextMenuItem() {
await this.stateService.setDisableContextMenuItem(this.disableContextMenuItem);
this.messagingService.send('bgUpdateContextMenu');
this.messagingService.send("bgUpdateContextMenu");
}
async updateAutoTotpCopy() {
@ -130,7 +135,7 @@ export class OptionsComponent implements OnInit {
async updateDisableBadgeCounter() {
await this.stateService.setDisableBadgeCounter(this.disableBadgeCounter);
this.messagingService.send('bgUpdateContextMenu');
this.messagingService.send("bgUpdateContextMenu");
}
async updateShowCards() {

View File

@ -1,31 +1,36 @@
import { CurrencyPipe } from '@angular/common';
import { Component } from '@angular/core';
import { CurrencyPipe } from "@angular/common";
import { Component } from "@angular/core";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PremiumComponent as BasePremiumComponent } from 'jslib-angular/components/premium.component';
import { StateService } from '../../services/abstractions/state.service';
import { PremiumComponent as BasePremiumComponent } from "jslib-angular/components/premium.component";
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-premium',
templateUrl: 'premium.component.html',
selector: "app-premium",
templateUrl: "premium.component.html",
})
export class PremiumComponent extends BasePremiumComponent {
priceString: string;
constructor(i18nService: I18nService, platformUtilsService: PlatformUtilsService,
apiService: ApiService, logService: LogService, stateService: StateService,
private currencyPipe: CurrencyPipe) {
constructor(
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
apiService: ApiService,
logService: LogService,
stateService: StateService,
private currencyPipe: CurrencyPipe
) {
super(i18nService, platformUtilsService, apiService, logService, stateService);
// Support old price string. Can be removed in future once all translations are properly updated.
const thePrice = this.currencyPipe.transform(this.price, '$');
this.priceString = i18nService.t('premiumPrice', thePrice);
if (this.priceString.indexOf('%price%') > -1) {
this.priceString = this.priceString.replace('%price%', thePrice);
const thePrice = this.currencyPipe.transform(this.price, "$");
this.priceString = i18nService.t("premiumPrice", thePrice);
if (this.priceString.indexOf("%price%") > -1) {
this.priceString = this.priceString.replace("%price%", thePrice);
}
}
}

View File

@ -1,52 +1,47 @@
import {
Component,
ElementRef,
OnInit,
ViewChild,
} from '@angular/core';
import { FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import Swal from 'sweetalert2/src/sweetalert2.js';
import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { FormControl } from "@angular/forms";
import { Router } from "@angular/router";
import Swal from "sweetalert2/src/sweetalert2.js";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { DeviceType } from 'jslib-common/enums/deviceType';
import { DeviceType } from "jslib-common/enums/deviceType";
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { EnvironmentService } from 'jslib-common/abstractions/environment.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { KeyConnectorService } from 'jslib-common/abstractions/keyConnector.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { VaultTimeoutService } from 'jslib-common/abstractions/vaultTimeout.service';
import { PopupUtilsService } from '../services/popup-utils.service';
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { EnvironmentService } from "jslib-common/abstractions/environment.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { KeyConnectorService } from "jslib-common/abstractions/keyConnector.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { PopupUtilsService } from "../services/popup-utils.service";
import { ModalService } from 'jslib-angular/services/modal.service';
import { ModalService } from "jslib-angular/services/modal.service";
import { StateService } from '../../services/abstractions/state.service';
import { SetPinComponent } from '../components/set-pin.component';
import { StateService } from "../../services/abstractions/state.service";
import { SetPinComponent } from "../components/set-pin.component";
const RateUrls = {
[DeviceType.ChromeExtension]:
'https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb/reviews',
"https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb/reviews",
[DeviceType.FirefoxExtension]:
'https://addons.mozilla.org/en-US/firefox/addon/bitwarden-password-manager/#reviews',
"https://addons.mozilla.org/en-US/firefox/addon/bitwarden-password-manager/#reviews",
[DeviceType.OperaExtension]:
'https://addons.opera.com/en/extensions/details/bitwarden-free-password-manager/#feedback-container',
"https://addons.opera.com/en/extensions/details/bitwarden-free-password-manager/#feedback-container",
[DeviceType.EdgeExtension]:
'https://microsoftedge.microsoft.com/addons/detail/jbkfoedolllekgbhcbcoahefnbanhhlh',
"https://microsoftedge.microsoft.com/addons/detail/jbkfoedolllekgbhcbcoahefnbanhhlh",
[DeviceType.VivaldiExtension]:
'https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb/reviews',
[DeviceType.SafariExtension]:
'https://apps.apple.com/app/bitwarden/id1352778147',
"https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb/reviews",
[DeviceType.SafariExtension]: "https://apps.apple.com/app/bitwarden/id1352778147",
};
@Component({
selector: 'app-settings',
templateUrl: 'settings.component.html',
selector: "app-settings",
templateUrl: "settings.component.html",
})
export class SettingsComponent implements OnInit {
@ViewChild('vaultTimeoutActionSelect', { read: ElementRef, static: true }) vaultTimeoutActionSelectRef: ElementRef;
@ViewChild("vaultTimeoutActionSelect", { read: ElementRef, static: true })
vaultTimeoutActionSelectRef: ElementRef;
vaultTimeouts: any[];
vaultTimeoutActions: any[];
vaultTimeoutAction: string;
@ -59,40 +54,46 @@ export class SettingsComponent implements OnInit {
vaultTimeout: FormControl = new FormControl(null);
constructor(private platformUtilsService: PlatformUtilsService, private i18nService: I18nService,
constructor(
private platformUtilsService: PlatformUtilsService,
private i18nService: I18nService,
private vaultTimeoutService: VaultTimeoutService,
public messagingService: MessagingService, private router: Router,
private environmentService: EnvironmentService, private cryptoService: CryptoService,
private stateService: StateService, private popupUtilsService: PopupUtilsService,
public messagingService: MessagingService,
private router: Router,
private environmentService: EnvironmentService,
private cryptoService: CryptoService,
private stateService: StateService,
private popupUtilsService: PopupUtilsService,
private modalService: ModalService,
private keyConnectorService: KeyConnectorService) {
}
private keyConnectorService: KeyConnectorService
) {}
async ngOnInit() {
const showOnLocked = !this.platformUtilsService.isFirefox() && !this.platformUtilsService.isSafari();
const showOnLocked =
!this.platformUtilsService.isFirefox() && !this.platformUtilsService.isSafari();
this.vaultTimeouts = [
{ name: this.i18nService.t('immediately'), value: 0 },
{ name: this.i18nService.t('oneMinute'), value: 1 },
{ name: this.i18nService.t('fiveMinutes'), value: 5 },
{ name: this.i18nService.t('fifteenMinutes'), value: 15 },
{ name: this.i18nService.t('thirtyMinutes'), value: 30 },
{ name: this.i18nService.t('oneHour'), value: 60 },
{ name: this.i18nService.t('fourHours'), value: 240 },
{ name: this.i18nService.t("immediately"), value: 0 },
{ name: this.i18nService.t("oneMinute"), value: 1 },
{ name: this.i18nService.t("fiveMinutes"), value: 5 },
{ name: this.i18nService.t("fifteenMinutes"), value: 15 },
{ name: this.i18nService.t("thirtyMinutes"), value: 30 },
{ name: this.i18nService.t("oneHour"), value: 60 },
{ name: this.i18nService.t("fourHours"), value: 240 },
// { name: i18nService.t('onIdle'), value: -4 },
// { name: i18nService.t('onSleep'), value: -3 },
];
if (showOnLocked) {
this.vaultTimeouts.push({ name: this.i18nService.t('onLocked'), value: -2 });
this.vaultTimeouts.push({ name: this.i18nService.t("onLocked"), value: -2 });
}
this.vaultTimeouts.push({ name: this.i18nService.t('onRestart'), value: -1 });
this.vaultTimeouts.push({ name: this.i18nService.t('never'), value: null });
this.vaultTimeouts.push({ name: this.i18nService.t("onRestart"), value: -1 });
this.vaultTimeouts.push({ name: this.i18nService.t("never"), value: null });
this.vaultTimeoutActions = [
{ name: this.i18nService.t('lock'), value: 'lock' },
{ name: this.i18nService.t('logOut'), value: 'logOut' },
{ name: this.i18nService.t("lock"), value: "lock" },
{ name: this.i18nService.t("logOut"), value: "logOut" },
];
let timeout = await this.vaultTimeoutService.getVaultTimeout();
@ -103,27 +104,32 @@ export class SettingsComponent implements OnInit {
this.vaultTimeout.setValue(timeout);
}
this.previousVaultTimeout = this.vaultTimeout.value;
this.vaultTimeout.valueChanges.subscribe(value => {
this.vaultTimeout.valueChanges.subscribe((value) => {
this.saveVaultTimeout(value);
});
const action = await this.stateService.getVaultTimeoutAction();
this.vaultTimeoutAction = action == null ? 'lock' : action;
this.vaultTimeoutAction = action == null ? "lock" : action;
const pinSet = await this.vaultTimeoutService.isPinLockSet();
this.pin = pinSet[0] || pinSet[1];
this.supportsBiometric = await this.platformUtilsService.supportsBiometric();
this.biometric = await this.vaultTimeoutService.isBiometricLockSet();
this.disableAutoBiometricsPrompt = await this.stateService.getDisableAutoBiometricsPrompt() ?? true;
this.showChangeMasterPass = !await this.keyConnectorService.getUsesKeyConnector();
this.disableAutoBiometricsPrompt =
(await this.stateService.getDisableAutoBiometricsPrompt()) ?? true;
this.showChangeMasterPass = !(await this.keyConnectorService.getUsesKeyConnector());
}
async saveVaultTimeout(newValue: number) {
if (newValue == null) {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('neverLockWarning'), null,
this.i18nService.t('yes'), this.i18nService.t('cancel'), 'warning');
this.i18nService.t("neverLockWarning"),
null,
this.i18nService.t("yes"),
this.i18nService.t("cancel"),
"warning"
);
if (!confirmed) {
this.vaultTimeout.setValue(this.previousVaultTimeout);
return;
@ -131,28 +137,35 @@ export class SettingsComponent implements OnInit {
}
if (!this.vaultTimeout.valid) {
this.platformUtilsService.showToast('error', null, this.i18nService.t('vaultTimeoutToLarge'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("vaultTimeoutToLarge"));
return;
}
this.previousVaultTimeout = this.vaultTimeout.value;
await this.vaultTimeoutService.setVaultTimeoutOptions(this.vaultTimeout.value, this.vaultTimeoutAction);
await this.vaultTimeoutService.setVaultTimeoutOptions(
this.vaultTimeout.value,
this.vaultTimeoutAction
);
if (this.previousVaultTimeout == null) {
this.messagingService.send('bgReseedStorage');
this.messagingService.send("bgReseedStorage");
}
}
async saveVaultTimeoutAction(newValue: string) {
if (newValue === 'logOut') {
if (newValue === "logOut") {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('vaultTimeoutLogOutConfirmation'),
this.i18nService.t('vaultTimeoutLogOutConfirmationTitle'),
this.i18nService.t('yes'), this.i18nService.t('cancel'), 'warning');
this.i18nService.t("vaultTimeoutLogOutConfirmation"),
this.i18nService.t("vaultTimeoutLogOutConfirmationTitle"),
this.i18nService.t("yes"),
this.i18nService.t("cancel"),
"warning"
);
if (!confirmed) {
this.vaultTimeoutActions.forEach((option: any, i) => {
if (option.value === this.vaultTimeoutAction) {
this.vaultTimeoutActionSelectRef.nativeElement.value = i + ': ' + this.vaultTimeoutAction;
this.vaultTimeoutActionSelectRef.nativeElement.value =
i + ": " + this.vaultTimeoutAction;
}
});
return;
@ -160,12 +173,15 @@ export class SettingsComponent implements OnInit {
}
if (!this.vaultTimeout.valid) {
this.platformUtilsService.showToast('error', null, this.i18nService.t('vaultTimeoutToLarge'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("vaultTimeoutToLarge"));
return;
}
this.vaultTimeoutAction = newValue;
await this.vaultTimeoutService.setVaultTimeoutOptions(this.vaultTimeout.value, this.vaultTimeoutAction);
await this.vaultTimeoutService.setVaultTimeoutOptions(
this.vaultTimeout.value,
this.vaultTimeoutAction
);
}
async updatePin() {
@ -186,18 +202,20 @@ export class SettingsComponent implements OnInit {
async updateBiometric() {
if (this.biometric && this.supportsBiometric) {
let granted;
try {
granted = await BrowserApi.requestPermission({ permissions: ['nativeMessaging'] });
granted = await BrowserApi.requestPermission({ permissions: ["nativeMessaging"] });
} catch (e) {
// tslint:disable-next-line
console.error(e);
if (this.platformUtilsService.isFirefox() && this.popupUtilsService.inSidebar(window)) {
await this.platformUtilsService.showDialog(
this.i18nService.t('nativeMessaginPermissionSidebarDesc'), this.i18nService.t('nativeMessaginPermissionSidebarTitle'),
this.i18nService.t('ok'), null);
this.i18nService.t("nativeMessaginPermissionSidebarDesc"),
this.i18nService.t("nativeMessaginPermissionSidebarTitle"),
this.i18nService.t("ok"),
null
);
this.biometric = false;
return;
}
@ -205,8 +223,11 @@ export class SettingsComponent implements OnInit {
if (!granted) {
await this.platformUtilsService.showDialog(
this.i18nService.t('nativeMessaginPermissionErrorDesc'), this.i18nService.t('nativeMessaginPermissionErrorTitle'),
this.i18nService.t('ok'), null);
this.i18nService.t("nativeMessaginPermissionErrorDesc"),
this.i18nService.t("nativeMessaginPermissionErrorTitle"),
this.i18nService.t("ok"),
null
);
this.biometric = false;
return;
}
@ -214,12 +235,12 @@ export class SettingsComponent implements OnInit {
const submitted = Swal.fire({
heightAuto: false,
buttonsStyling: false,
titleText: this.i18nService.t('awaitDesktop'),
text: this.i18nService.t('awaitDesktopDesc'),
icon: 'info',
titleText: this.i18nService.t("awaitDesktop"),
text: this.i18nService.t("awaitDesktopDesc"),
icon: "info",
iconHtml: '<i class="swal-custom-icon fa fa-info-circle text-info"></i>',
showCancelButton: true,
cancelButtonText: this.i18nService.t('cancel'),
cancelButtonText: this.i18nService.t("cancel"),
showConfirmButton: false,
allowOutsideClick: false,
});
@ -228,20 +249,27 @@ export class SettingsComponent implements OnInit {
await this.cryptoService.toggleKey();
await Promise.race([
submitted.then(async result => {
submitted.then(async (result) => {
if (result.dismiss === Swal.DismissReason.cancel) {
this.biometric = false;
await this.stateService.setBiometricAwaitingAcceptance(null);
}
}),
this.platformUtilsService.authenticateBiometric().then(result => {
this.platformUtilsService
.authenticateBiometric()
.then((result) => {
this.biometric = result;
Swal.close();
if (this.biometric === false) {
this.platformUtilsService.showToast('error', this.i18nService.t('errorEnableBiometricTitle'), this.i18nService.t('errorEnableBiometricDesc'));
this.platformUtilsService.showToast(
"error",
this.i18nService.t("errorEnableBiometricTitle"),
this.i18nService.t("errorEnableBiometricDesc")
);
}
}).catch(e => {
})
.catch((e) => {
// Handle connection errors
this.biometric = false;
}),
@ -262,37 +290,49 @@ export class SettingsComponent implements OnInit {
async logOut() {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('logOutConfirmation'), this.i18nService.t('logOut'),
this.i18nService.t('yes'), this.i18nService.t('cancel'));
this.i18nService.t("logOutConfirmation"),
this.i18nService.t("logOut"),
this.i18nService.t("yes"),
this.i18nService.t("cancel")
);
if (confirmed) {
this.messagingService.send('logout');
this.messagingService.send("logout");
}
}
async changePassword() {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('changeMasterPasswordConfirmation'), this.i18nService.t('changeMasterPassword'),
this.i18nService.t('yes'), this.i18nService.t('cancel'));
this.i18nService.t("changeMasterPasswordConfirmation"),
this.i18nService.t("changeMasterPassword"),
this.i18nService.t("yes"),
this.i18nService.t("cancel")
);
if (confirmed) {
BrowserApi.createNewTab('https://help.bitwarden.com/article/change-your-master-password/');
BrowserApi.createNewTab("https://help.bitwarden.com/article/change-your-master-password/");
}
}
async twoStep() {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('twoStepLoginConfirmation'), this.i18nService.t('twoStepLogin'),
this.i18nService.t('yes'), this.i18nService.t('cancel'));
this.i18nService.t("twoStepLoginConfirmation"),
this.i18nService.t("twoStepLogin"),
this.i18nService.t("yes"),
this.i18nService.t("cancel")
);
if (confirmed) {
BrowserApi.createNewTab('https://help.bitwarden.com/article/setup-two-step-login/');
BrowserApi.createNewTab("https://help.bitwarden.com/article/setup-two-step-login/");
}
}
async share() {
const confirmed = await this.platformUtilsService.showDialog(
this.i18nService.t('learnOrgConfirmation'), this.i18nService.t('learnOrg'),
this.i18nService.t('yes'), this.i18nService.t('cancel'));
this.i18nService.t("learnOrgConfirmation"),
this.i18nService.t("learnOrg"),
this.i18nService.t("yes"),
this.i18nService.t("cancel")
);
if (confirmed) {
BrowserApi.createNewTab('https://help.bitwarden.com/article/what-is-an-organization/');
BrowserApi.createNewTab("https://help.bitwarden.com/article/what-is-an-organization/");
}
}
@ -302,24 +342,28 @@ export class SettingsComponent implements OnInit {
}
import() {
BrowserApi.createNewTab('https://help.bitwarden.com/article/import-data/');
BrowserApi.createNewTab("https://help.bitwarden.com/article/import-data/");
}
export() {
this.router.navigate(['/export']);
this.router.navigate(["/export"]);
}
help() {
BrowserApi.createNewTab('https://help.bitwarden.com/');
BrowserApi.createNewTab("https://help.bitwarden.com/");
}
about() {
const year = (new Date()).getFullYear();
const year = new Date().getFullYear();
const versionText = document.createTextNode(
this.i18nService.t('version') + ': ' + BrowserApi.getApplicationVersion());
const div = document.createElement('div');
div.innerHTML = `<p class="text-center"><i class="fa fa-shield fa-3x" aria-hidden="true"></i></p>
<p class="text-center"><b>Bitwarden</b><br>&copy; Bitwarden Inc. 2015-` + year + `</p>`;
this.i18nService.t("version") + ": " + BrowserApi.getApplicationVersion()
);
const div = document.createElement("div");
div.innerHTML =
`<p class="text-center"><i class="fa fa-shield fa-3x" aria-hidden="true"></i></p>
<p class="text-center"><b>Bitwarden</b><br>&copy; Bitwarden Inc. 2015-` +
year +
`</p>`;
div.appendChild(versionText);
Swal.fire({
@ -328,17 +372,19 @@ export class SettingsComponent implements OnInit {
html: div,
showConfirmButton: false,
showCancelButton: true,
cancelButtonText: this.i18nService.t('close'),
cancelButtonText: this.i18nService.t("close"),
});
}
async fingerprint() {
const fingerprint = await this.cryptoService.getFingerprint(await this.stateService.getUserId());
const p = document.createElement('p');
p.innerText = this.i18nService.t('yourAccountsFingerprint') + ':';
const p2 = document.createElement('p');
p2.innerText = fingerprint.join('-');
const div = document.createElement('div');
const fingerprint = await this.cryptoService.getFingerprint(
await this.stateService.getUserId()
);
const p = document.createElement("p");
p.innerText = this.i18nService.t("yourAccountsFingerprint") + ":";
const p2 = document.createElement("p");
p2.innerText = fingerprint.join("-");
const div = document.createElement("div");
div.appendChild(p);
div.appendChild(p2);
@ -347,13 +393,13 @@ export class SettingsComponent implements OnInit {
buttonsStyling: false,
html: div,
showCancelButton: true,
cancelButtonText: this.i18nService.t('close'),
cancelButtonText: this.i18nService.t("close"),
showConfirmButton: true,
confirmButtonText: this.i18nService.t('learnMore'),
confirmButtonText: this.i18nService.t("learnMore"),
});
if (result.value) {
this.platformUtilsService.launchUri('https://help.bitwarden.com/article/fingerprint-phrase/');
this.platformUtilsService.launchUri("https://help.bitwarden.com/article/fingerprint-phrase/");
}
}

View File

@ -1,39 +1,36 @@
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { Location } from "@angular/common";
import { Component } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { AuditService } from 'jslib-common/abstractions/audit.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { EventService } from 'jslib-common/abstractions/event.service';
import { FolderService } from 'jslib-common/abstractions/folder.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { OrganizationService } from 'jslib-common/abstractions/organization.service';
import { PasswordRepromptService } from 'jslib-common/abstractions/passwordReprompt.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { PolicyService } from 'jslib-common/abstractions/policy.service';
import { StateService } from '../../services/abstractions/state.service';
import { AuditService } from "jslib-common/abstractions/audit.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { EventService } from "jslib-common/abstractions/event.service";
import { FolderService } from "jslib-common/abstractions/folder.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { OrganizationService } from "jslib-common/abstractions/organization.service";
import { PasswordRepromptService } from "jslib-common/abstractions/passwordReprompt.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { PolicyService } from "jslib-common/abstractions/policy.service";
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { LoginUriView } from 'jslib-common/models/view/loginUriView';
import { LoginUriView } from "jslib-common/models/view/loginUriView";
import { AddEditComponent as BaseAddEditComponent } from 'jslib-angular/components/add-edit.component';
import { AddEditComponent as BaseAddEditComponent } from "jslib-angular/components/add-edit.component";
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherType } from "jslib-common/enums/cipherType";
@Component({
selector: 'app-vault-add-edit',
templateUrl: 'add-edit.component.html',
selector: "app-vault-add-edit",
templateUrl: "add-edit.component.html",
})
export class AddEditComponent extends BaseAddEditComponent {
currentUris: string[];
@ -41,23 +38,46 @@ export class AddEditComponent extends BaseAddEditComponent {
openAttachmentsInPopup: boolean;
showAutoFillOnPageLoadOptions: boolean;
constructor(cipherService: CipherService, folderService: FolderService,
i18nService: I18nService, platformUtilsService: PlatformUtilsService,
auditService: AuditService, stateService: StateService, collectionService: CollectionService,
messagingService: MessagingService, private route: ActivatedRoute,
private router: Router, private location: Location,
eventService: EventService, policyService: PolicyService,
private popupUtilsService: PopupUtilsService, organizationService: OrganizationService,
passwordRepromptService: PasswordRepromptService, logService: LogService) {
super(cipherService, folderService, i18nService, platformUtilsService,
auditService, stateService, collectionService, messagingService,
eventService, policyService, logService, passwordRepromptService, organizationService);
constructor(
cipherService: CipherService,
folderService: FolderService,
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
auditService: AuditService,
stateService: StateService,
collectionService: CollectionService,
messagingService: MessagingService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
eventService: EventService,
policyService: PolicyService,
private popupUtilsService: PopupUtilsService,
organizationService: OrganizationService,
passwordRepromptService: PasswordRepromptService,
logService: LogService
) {
super(
cipherService,
folderService,
i18nService,
platformUtilsService,
auditService,
stateService,
collectionService,
messagingService,
eventService,
policyService,
logService,
passwordRepromptService,
organizationService
);
}
async ngOnInit() {
await super.ngOnInit();
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (params.cipherId) {
this.cipherId = params.cipherId;
}
@ -65,7 +85,7 @@ export class AddEditComponent extends BaseAddEditComponent {
this.folderId = params.folderId;
}
if (params.collectionId) {
const collection = this.writeableCollections.find(c => c.id === params.collectionId);
const collection = this.writeableCollections.find((c) => c.id === params.collectionId);
if (collection != null) {
this.collectionIds = [collection.id];
this.organizationId = collection.organizationId;
@ -78,17 +98,23 @@ export class AddEditComponent extends BaseAddEditComponent {
this.editMode = !params.cipherId;
if (params.cloneMode != null) {
this.cloneMode = params.cloneMode === 'true';
this.cloneMode = params.cloneMode === "true";
}
await this.load();
if (!this.editMode || this.cloneMode) {
if (!this.popupUtilsService.inPopout(window) && params.name &&
(this.cipher.name == null || this.cipher.name === '')) {
if (
!this.popupUtilsService.inPopout(window) &&
params.name &&
(this.cipher.name == null || this.cipher.name === "")
) {
this.cipher.name = params.name;
}
if (!this.popupUtilsService.inPopout(window) && params.uri &&
(this.cipher.login.uris[0].uri == null || this.cipher.login.uris[0].uri === '')) {
if (
!this.popupUtilsService.inPopout(window) &&
params.uri &&
(this.cipher.login.uris[0].uri == null || this.cipher.login.uris[0].uri === "")
) {
this.cipher.login.uris[0].uri = params.uri;
}
}
@ -97,17 +123,19 @@ export class AddEditComponent extends BaseAddEditComponent {
});
if (!this.editMode) {
const tabs = await BrowserApi.tabsQuery({ windowType: 'normal' });
this.currentUris = tabs == null ? null :
tabs.filter(tab => tab.url != null && tab.url !== '').map(tab => tab.url);
const tabs = await BrowserApi.tabsQuery({ windowType: "normal" });
this.currentUris =
tabs == null
? null
: tabs.filter((tab) => tab.url != null && tab.url !== "").map((tab) => tab.url);
}
window.setTimeout(() => {
if (!this.editMode) {
if (this.cipher.name != null && this.cipher.name !== '') {
document.getElementById('loginUsername').focus();
if (this.cipher.name != null && this.cipher.name !== "") {
document.getElementById("loginUsername").focus();
} else {
document.getElementById('name').focus();
document.getElementById("name").focus();
}
}
}, 200);
@ -115,14 +143,15 @@ export class AddEditComponent extends BaseAddEditComponent {
async load() {
await super.load();
this.showAutoFillOnPageLoadOptions = this.cipher.type === CipherType.Login &&
await this.stateService.getEnableAutoFillOnPageLoad();
this.showAutoFillOnPageLoadOptions =
this.cipher.type === CipherType.Login &&
(await this.stateService.getEnableAutoFillOnPageLoad());
}
async submit(): Promise<boolean> {
if (await super.submit()) {
if (this.cloneMode) {
this.router.navigate(['/tabs/vault']);
this.router.navigate(["/tabs/vault"]);
} else {
this.location.back();
}
@ -136,19 +165,20 @@ export class AddEditComponent extends BaseAddEditComponent {
super.attachments();
if (this.openAttachmentsInPopup) {
const destinationUrl = this.router.createUrlTree(['/attachments'], { queryParams: { cipherId: this.cipher.id } }).toString();
const currentBaseUrl = window.location.href.replace(this.router.url, '');
const destinationUrl = this.router
.createUrlTree(["/attachments"], { queryParams: { cipherId: this.cipher.id } })
.toString();
const currentBaseUrl = window.location.href.replace(this.router.url, "");
this.popupUtilsService.popOut(window, currentBaseUrl + destinationUrl);
} else {
this.router.navigate(['/attachments'], { queryParams: { cipherId: this.cipher.id } });
this.router.navigate(["/attachments"], { queryParams: { cipherId: this.cipher.id } });
}
}
editCollections() {
super.editCollections();
if (this.cipher.organizationId != null) {
this.router.navigate(['/collections'], { queryParams: { cipherId: this.cipher.id } });
this.router.navigate(["/collections"], { queryParams: { cipherId: this.cipher.id } });
}
}
@ -162,10 +192,12 @@ export class AddEditComponent extends BaseAddEditComponent {
if (confirmed) {
this.stateService.setAddEditCipherInfo({
cipher: this.cipher,
collectionIds: this.collections == null ? [] :
this.collections.filter(c => (c as any).checked).map(c => c.id),
collectionIds:
this.collections == null
? []
: this.collections.filter((c) => (c as any).checked).map((c) => c.id),
});
this.router.navigate(['generator']);
this.router.navigate(["generator"]);
}
return confirmed;
}
@ -173,18 +205,21 @@ export class AddEditComponent extends BaseAddEditComponent {
async delete(): Promise<boolean> {
const confirmed = await super.delete();
if (confirmed) {
this.router.navigate(['/tabs/vault']);
this.router.navigate(["/tabs/vault"]);
}
return confirmed;
}
toggleUriInput(uri: LoginUriView) {
const u = (uri as any);
const u = uri as any;
u.showCurrentUris = !u.showCurrentUris;
}
allowOwnershipOptions(): boolean {
return (!this.editMode || this.cloneMode) && this.ownershipOptions
&& (this.ownershipOptions.length > 1 || !this.allowPersonal);
return (
(!this.editMode || this.cloneMode) &&
this.ownershipOptions &&
(this.ownershipOptions.length > 1 || !this.allowPersonal)
);
}
}

View File

@ -1,36 +1,51 @@
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from "@angular/common";
import { Component } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { AttachmentsComponent as BaseAttachmentsComponent } from 'jslib-angular/components/attachments.component';
import { StateService } from '../../services/abstractions/state.service';
import { AttachmentsComponent as BaseAttachmentsComponent } from "jslib-angular/components/attachments.component";
import { StateService } from "../../services/abstractions/state.service";
@Component({
selector: 'app-vault-attachments',
templateUrl: 'attachments.component.html',
selector: "app-vault-attachments",
templateUrl: "attachments.component.html",
})
export class AttachmentsComponent extends BaseAttachmentsComponent {
openedAttachmentsInPopup: boolean;
constructor(cipherService: CipherService, i18nService: I18nService,
cryptoService: CryptoService, platformUtilsService: PlatformUtilsService,
apiService: ApiService, private location: Location,
private route: ActivatedRoute, stateService: StateService, logService: LogService) {
super(cipherService, i18nService, cryptoService, platformUtilsService,
apiService, window, logService, stateService);
constructor(
cipherService: CipherService,
i18nService: I18nService,
cryptoService: CryptoService,
platformUtilsService: PlatformUtilsService,
apiService: ApiService,
private location: Location,
private route: ActivatedRoute,
stateService: StateService,
logService: LogService
) {
super(
cipherService,
i18nService,
cryptoService,
platformUtilsService,
apiService,
window,
logService,
stateService
);
}
async ngOnInit() {
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
this.cipherId = params.cipherId;
await this.init();
});

View File

@ -1,47 +1,38 @@
import { Location } from '@angular/common';
import {
ChangeDetectorRef,
Component,
NgZone,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { Location } from "@angular/common";
import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { FolderService } from 'jslib-common/abstractions/folder.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { SearchService } from 'jslib-common/abstractions/search.service';
import { StateService } from '../../services/abstractions/state.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { FolderService } from "jslib-common/abstractions/folder.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { SearchService } from "jslib-common/abstractions/search.service";
import { StateService } from "../../services/abstractions/state.service";
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherType } from "jslib-common/enums/cipherType";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CollectionView } from 'jslib-common/models/view/collectionView';
import { FolderView } from 'jslib-common/models/view/folderView';
import { CipherView } from "jslib-common/models/view/cipherView";
import { CollectionView } from "jslib-common/models/view/collectionView";
import { FolderView } from "jslib-common/models/view/folderView";
import { TreeNode } from 'jslib-common/models/domain/treeNode';
import { TreeNode } from "jslib-common/models/domain/treeNode";
import { CiphersComponent as BaseCiphersComponent } from 'jslib-angular/components/ciphers.component';
import { CiphersComponent as BaseCiphersComponent } from "jslib-angular/components/ciphers.component";
import { BrowserComponentState } from '../../models/browserComponentState';
import { PopupUtilsService } from '../services/popup-utils.service';
import { BrowserComponentState } from "../../models/browserComponentState";
import { PopupUtilsService } from "../services/popup-utils.service";
const ComponentId = 'CiphersComponent';
const ComponentId = "CiphersComponent";
@Component({
selector: 'app-vault-ciphers',
templateUrl: 'ciphers.component.html',
selector: "app-vault-ciphers",
templateUrl: "ciphers.component.html",
})
export class CiphersComponent extends BaseCiphersComponent implements OnInit, OnDestroy {
groupingTitle: string;
@ -56,23 +47,33 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
private selectedTimeout: number;
private preventSelected = false;
private applySavedState = true;
private scrollingContainer = 'cdk-virtual-scroll-viewport';
private scrollingContainer = "cdk-virtual-scroll-viewport";
constructor(searchService: SearchService, private route: ActivatedRoute,
private router: Router, private location: Location,
private ngZone: NgZone, private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef, private stateService: StateService,
private popupUtils: PopupUtilsService, private i18nService: I18nService,
private folderService: FolderService, private collectionService: CollectionService,
private platformUtilsService: PlatformUtilsService, private cipherService: CipherService) {
constructor(
searchService: SearchService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
private ngZone: NgZone,
private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef,
private stateService: StateService,
private popupUtils: PopupUtilsService,
private i18nService: I18nService,
private folderService: FolderService,
private collectionService: CollectionService,
private platformUtilsService: PlatformUtilsService,
private cipherService: CipherService
) {
super(searchService);
this.applySavedState = (window as any).previousPopupUrl != null &&
!(window as any).previousPopupUrl.startsWith('/ciphers');
this.applySavedState =
(window as any).previousPopupUrl != null &&
!(window as any).previousPopupUrl.startsWith("/ciphers");
}
async ngOnInit() {
this.searchTypeSearch = !this.platformUtilsService.isSafari();
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (this.applySavedState) {
this.state = await this.stateService.getBrowserCipherComponentState();
if (this.state?.searchText) {
@ -81,61 +82,70 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
}
if (params.deleted) {
this.groupingTitle = this.i18nService.t('trash');
this.searchPlaceholder = this.i18nService.t('searchTrash');
this.groupingTitle = this.i18nService.t("trash");
this.searchPlaceholder = this.i18nService.t("searchTrash");
await this.load(null, true);
} else if (params.type) {
this.searchPlaceholder = this.i18nService.t('searchType');
this.searchPlaceholder = this.i18nService.t("searchType");
this.type = parseInt(params.type, null);
switch (this.type) {
case CipherType.Login:
this.groupingTitle = this.i18nService.t('logins');
this.groupingTitle = this.i18nService.t("logins");
break;
case CipherType.Card:
this.groupingTitle = this.i18nService.t('cards');
this.groupingTitle = this.i18nService.t("cards");
break;
case CipherType.Identity:
this.groupingTitle = this.i18nService.t('identities');
this.groupingTitle = this.i18nService.t("identities");
break;
case CipherType.SecureNote:
this.groupingTitle = this.i18nService.t('secureNotes');
this.groupingTitle = this.i18nService.t("secureNotes");
break;
default:
break;
}
await this.load(c => c.type === this.type);
await this.load((c) => c.type === this.type);
} else if (params.folderId) {
this.folderId = params.folderId === 'none' ? null : params.folderId;
this.searchPlaceholder = this.i18nService.t('searchFolder');
this.folderId = params.folderId === "none" ? null : params.folderId;
this.searchPlaceholder = this.i18nService.t("searchFolder");
if (this.folderId != null) {
const folderNode = await this.folderService.getNested(this.folderId);
if (folderNode != null && folderNode.node != null) {
this.groupingTitle = folderNode.node.name;
this.nestedFolders = folderNode.children != null && folderNode.children.length > 0 ?
folderNode.children : null;
this.nestedFolders =
folderNode.children != null && folderNode.children.length > 0
? folderNode.children
: null;
}
} else {
this.groupingTitle = this.i18nService.t('noneFolder');
this.groupingTitle = this.i18nService.t("noneFolder");
}
await this.load(c => c.folderId === this.folderId);
await this.load((c) => c.folderId === this.folderId);
} else if (params.collectionId) {
this.collectionId = params.collectionId;
this.searchPlaceholder = this.i18nService.t('searchCollection');
this.searchPlaceholder = this.i18nService.t("searchCollection");
const collectionNode = await this.collectionService.getNested(this.collectionId);
if (collectionNode != null && collectionNode.node != null) {
this.groupingTitle = collectionNode.node.name;
this.nestedCollections = collectionNode.children != null && collectionNode.children.length > 0 ?
collectionNode.children : null;
this.nestedCollections =
collectionNode.children != null && collectionNode.children.length > 0
? collectionNode.children
: null;
}
await this.load(c => c.collectionIds != null && c.collectionIds.indexOf(this.collectionId) > -1);
await this.load(
(c) => c.collectionIds != null && c.collectionIds.indexOf(this.collectionId) > -1
);
} else {
this.groupingTitle = this.i18nService.t('allItems');
this.groupingTitle = this.i18nService.t("allItems");
await this.load();
}
if (this.applySavedState && this.state != null) {
window.setTimeout(() => this.popupUtils.setContentScrollY(window, this.state?.scrollY,
this.scrollingContainer), 0);
window.setTimeout(
() =>
this.popupUtils.setContentScrollY(window, this.state?.scrollY, this.scrollingContainer),
0
);
}
await this.stateService.setBrowserCipherComponentState(null);
});
@ -143,7 +153,7 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
this.broadcasterService.subscribe(ComponentId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'syncCompleted':
case "syncCompleted":
if (message.successfully) {
window.setTimeout(() => {
this.refresh();
@ -168,7 +178,7 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
this.selectedTimeout = window.setTimeout(() => {
if (!this.preventSelected) {
super.selectCipher(cipher);
this.router.navigate(['/view-cipher'], { queryParams: { cipherId: cipher.id } });
this.router.navigate(["/view-cipher"], { queryParams: { cipherId: cipher.id } });
}
this.preventSelected = false;
}, 200);
@ -176,12 +186,12 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
selectFolder(folder: FolderView) {
if (folder.id != null) {
this.router.navigate(['/ciphers'], { queryParams: { folderId: folder.id } });
this.router.navigate(["/ciphers"], { queryParams: { folderId: folder.id } });
}
}
selectCollection(collection: CollectionView) {
this.router.navigate(['/ciphers'], { queryParams: { collectionId: collection.id } });
this.router.navigate(["/ciphers"], { queryParams: { collectionId: collection.id } });
}
async launchCipher(cipher: CipherView) {
@ -205,7 +215,7 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
return false;
}
super.addCipher();
this.router.navigate(['/add-cipher'], {
this.router.navigate(["/add-cipher"], {
queryParams: {
folderId: this.folderId,
type: this.type,
@ -215,14 +225,16 @@ export class CiphersComponent extends BaseCiphersComponent implements OnInit, On
}
back() {
(window as any).routeDirection = 'b';
(window as any).routeDirection = "b";
this.location.back();
}
showGroupings() {
return !this.isSearching() &&
return (
!this.isSearching() &&
((this.nestedFolders && this.nestedFolders.length) ||
(this.nestedCollections && this.nestedCollections.length));
(this.nestedCollections && this.nestedCollections.length))
);
}
private async saveState() {

View File

@ -1,24 +1,30 @@
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { first } from 'rxjs/operators';
import { Location } from "@angular/common";
import { Component } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { first } from "rxjs/operators";
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { CollectionsComponent as BaseCollectionsComponent } from 'jslib-angular/components/collections.component';
import { CollectionsComponent as BaseCollectionsComponent } from "jslib-angular/components/collections.component";
@Component({
selector: 'app-vault-collections',
templateUrl: 'collections.component.html',
selector: "app-vault-collections",
templateUrl: "collections.component.html",
})
export class CollectionsComponent extends BaseCollectionsComponent {
constructor(collectionService: CollectionService, platformUtilsService: PlatformUtilsService,
i18nService: I18nService, cipherService: CipherService,
private route: ActivatedRoute, private location: Location, logService: LogService) {
constructor(
collectionService: CollectionService,
platformUtilsService: PlatformUtilsService,
i18nService: I18nService,
cipherService: CipherService,
private route: ActivatedRoute,
private location: Location,
logService: LogService
) {
super(collectionService, platformUtilsService, i18nService, cipherService, logService);
}
@ -26,7 +32,7 @@ export class CollectionsComponent extends BaseCollectionsComponent {
this.onSavedCollections.subscribe(() => {
this.back();
});
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
this.cipherId = params.cipherId;
await this.load();
});

View File

@ -1,39 +1,33 @@
import {
ChangeDetectorRef,
Component,
NgZone,
OnDestroy,
OnInit,
} from '@angular/core';
import { Router } from '@angular/router';
import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { CipherRepromptType } from 'jslib-common/enums/cipherRepromptType';
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherRepromptType } from "jslib-common/enums/cipherRepromptType";
import { CipherType } from "jslib-common/enums/cipherType";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CipherView } from "jslib-common/models/view/cipherView";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { PasswordRepromptService } from 'jslib-common/abstractions/passwordReprompt.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { SearchService } from 'jslib-common/abstractions/search.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { PasswordRepromptService } from "jslib-common/abstractions/passwordReprompt.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { SearchService } from "jslib-common/abstractions/search.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { AutofillService } from '../../services/abstractions/autofill.service';
import { StateService } from '../../services/abstractions/state.service';
import { AutofillService } from "../../services/abstractions/autofill.service";
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
import { Utils } from 'jslib-common/misc/utils';
import { Utils } from "jslib-common/misc/utils";
const BroadcasterSubscriptionId = 'CurrentTabComponent';
const BroadcasterSubscriptionId = "CurrentTabComponent";
@Component({
selector: 'app-current-tab',
templateUrl: 'current-tab.component.html',
selector: "app-current-tab",
templateUrl: "current-tab.component.html",
})
export class CurrentTabComponent implements OnInit, OnDestroy {
pageDetails: any[] = [];
@ -52,14 +46,21 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
private loadedTimeout: number;
private searchTimeout: number;
constructor(private platformUtilsService: PlatformUtilsService, private cipherService: CipherService,
private popupUtilsService: PopupUtilsService, private autofillService: AutofillService,
private i18nService: I18nService, private router: Router,
private ngZone: NgZone, private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef, private syncService: SyncService,
private searchService: SearchService, private stateService: StateService,
private passwordRepromptService: PasswordRepromptService) {
}
constructor(
private platformUtilsService: PlatformUtilsService,
private cipherService: CipherService,
private popupUtilsService: PopupUtilsService,
private autofillService: AutofillService,
private i18nService: I18nService,
private router: Router,
private ngZone: NgZone,
private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef,
private syncService: SyncService,
private searchService: SearchService,
private stateService: StateService,
private passwordRepromptService: PasswordRepromptService
) {}
async ngOnInit() {
this.searchTypeSearch = !this.platformUtilsService.isSafari();
@ -68,14 +69,14 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
this.broadcasterService.subscribe(BroadcasterSubscriptionId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'syncCompleted':
case "syncCompleted":
if (this.loaded) {
window.setTimeout(() => {
this.load();
}, 500);
}
break;
case 'collectPageDetailsResponse':
case "collectPageDetailsResponse":
if (message.sender === BroadcasterSubscriptionId) {
this.pageDetails.push({
frameId: message.webExtSender.frameId,
@ -103,7 +104,7 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
}
window.setTimeout(() => {
document.getElementById('search').focus();
document.getElementById("search").focus();
}, 100);
}
@ -117,15 +118,18 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
}
addCipher() {
this.router.navigate(['/add-cipher'], { queryParams: { name: this.hostname, uri: this.url } });
this.router.navigate(["/add-cipher"], { queryParams: { name: this.hostname, uri: this.url } });
}
viewCipher(cipher: CipherView) {
this.router.navigate(['/view-cipher'], { queryParams: { cipherId: cipher.id } });
this.router.navigate(["/view-cipher"], { queryParams: { cipherId: cipher.id } });
}
async fillCipher(cipher: CipherView) {
if (cipher.reprompt !== CipherRepromptType.None && !await this.passwordRepromptService.showPasswordPrompt()) {
if (
cipher.reprompt !== CipherRepromptType.None &&
!(await this.passwordRepromptService.showPasswordPrompt())
) {
return;
}
@ -135,7 +139,7 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
}
if (this.pageDetails == null || this.pageDetails.length === 0) {
this.platformUtilsService.showToast('error', null, this.i18nService.t('autofillError'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("autofillError"));
return;
}
@ -159,7 +163,7 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
}
} catch {
this.ngZone.run(() => {
this.platformUtilsService.showToast('error', null, this.i18nService.t('autofillError'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("autofillError"));
this.changeDetectorRef.detectChanges();
});
}
@ -173,13 +177,13 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
return;
}
this.searchTimeout = window.setTimeout(async () => {
this.router.navigate(['/tabs/vault'], { queryParams: { searchText: this.searchText } });
this.router.navigate(["/tabs/vault"], { queryParams: { searchText: this.searchText } });
}, 200);
}
closeOnEsc(e: KeyboardEvent) {
// If input not empty, use browser default behavior of clearing input instead
if (e.key === 'Escape' && (this.searchText == null || this.searchText === '')) {
if (e.key === "Escape" && (this.searchText == null || this.searchText === "")) {
BrowserApi.closePopup(window);
}
}
@ -197,7 +201,7 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
this.hostname = Utils.getHostname(this.url);
this.pageDetails = [];
BrowserApi.tabSendMessage(tab, {
command: 'collectPageDetails',
command: "collectPageDetails",
tab: tab,
sender: BroadcasterSubscriptionId,
});
@ -212,14 +216,16 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
otherTypes.push(CipherType.Identity);
}
const ciphers = await this.cipherService.getAllDecryptedForUrl(this.url,
otherTypes.length > 0 ? otherTypes : null);
const ciphers = await this.cipherService.getAllDecryptedForUrl(
this.url,
otherTypes.length > 0 ? otherTypes : null
);
this.loginCiphers = [];
this.cardCiphers = [];
this.identityCiphers = [];
ciphers.forEach(c => {
ciphers.forEach((c) => {
switch (c.type) {
case CipherType.Login:
this.loginCiphers.push(c);
@ -235,7 +241,9 @@ export class CurrentTabComponent implements OnInit, OnDestroy {
}
});
this.loginCiphers = this.loginCiphers.sort((a, b) => this.cipherService.sortCiphersByLastUsedThenName(a, b));
this.loginCiphers = this.loginCiphers.sort((a, b) =>
this.cipherService.sortCiphersByLastUsedThenName(a, b)
);
this.loaded = true;
}
}

View File

@ -1,51 +1,44 @@
import { Location } from '@angular/common';
import {
ChangeDetectorRef,
Component,
NgZone,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { Location } from "@angular/common";
import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherType } from "jslib-common/enums/cipherType";
import { CipherView } from 'jslib-common/models/view/cipherView';
import { CollectionView } from 'jslib-common/models/view/collectionView';
import { FolderView } from 'jslib-common/models/view/folderView';
import { CipherView } from "jslib-common/models/view/cipherView";
import { CollectionView } from "jslib-common/models/view/collectionView";
import { FolderView } from "jslib-common/models/view/folderView";
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { FolderService } from 'jslib-common/abstractions/folder.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { SearchService } from 'jslib-common/abstractions/search.service';
import { SyncService } from 'jslib-common/abstractions/sync.service';
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { FolderService } from "jslib-common/abstractions/folder.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { SearchService } from "jslib-common/abstractions/search.service";
import { SyncService } from "jslib-common/abstractions/sync.service";
import { GroupingsComponent as BaseGroupingsComponent } from 'jslib-angular/components/groupings.component';
import { GroupingsComponent as BaseGroupingsComponent } from "jslib-angular/components/groupings.component";
import { StateService } from '../../services/abstractions/state.service';
import { PopupUtilsService } from '../services/popup-utils.service';
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from "../services/popup-utils.service";
const ComponentId = 'GroupingsComponent';
const ScopeStateId = ComponentId + 'Scope';
const ComponentId = "GroupingsComponent";
const ScopeStateId = ComponentId + "Scope";
@Component({
selector: 'app-vault-groupings',
templateUrl: 'groupings.component.html',
selector: "app-vault-groupings",
templateUrl: "groupings.component.html",
})
export class GroupingsComponent extends BaseGroupingsComponent implements OnInit, OnDestroy {
get showNoFolderCiphers(): boolean {
return this.noFolderCiphers != null && this.noFolderCiphers.length < this.noFolderListSize &&
this.collections.length === 0;
return (
this.noFolderCiphers != null &&
this.noFolderCiphers.length < this.noFolderListSize &&
this.collections.length === 0
);
}
get folderCount(): number {
@ -74,27 +67,38 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
private hasLoadedAllCiphers = false;
private allCiphers: CipherView[] = null;
constructor(collectionService: CollectionService, folderService: FolderService,
private cipherService: CipherService, private router: Router,
private ngZone: NgZone, private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef, private route: ActivatedRoute,
baseStateService: StateService, private popupUtils: PopupUtilsService,
private syncService: SyncService, private platformUtilsService: PlatformUtilsService,
private searchService: SearchService, private location: Location,
private browserStateService: StateService) {
constructor(
collectionService: CollectionService,
folderService: FolderService,
private cipherService: CipherService,
private router: Router,
private ngZone: NgZone,
private broadcasterService: BroadcasterService,
private changeDetectorRef: ChangeDetectorRef,
private route: ActivatedRoute,
baseStateService: StateService,
private popupUtils: PopupUtilsService,
private syncService: SyncService,
private platformUtilsService: PlatformUtilsService,
private searchService: SearchService,
private location: Location,
private browserStateService: StateService
) {
super(collectionService, folderService, baseStateService);
this.noFolderListSize = 100;
}
async ngOnInit() {
this.searchTypeSearch = !this.platformUtilsService.isSafari();
this.showLeftHeader = !(this.popupUtils.inSidebar(window) && this.platformUtilsService.isFirefox());
this.showLeftHeader = !(
this.popupUtils.inSidebar(window) && this.platformUtilsService.isFirefox()
);
await this.browserStateService.setBrowserCipherComponentState(null);
this.broadcasterService.subscribe(ComponentId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'syncCompleted':
case "syncCompleted":
window.setTimeout(() => {
this.load();
}, 500);
@ -108,13 +112,13 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
});
const restoredScopeState = await this.restoreState();
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
this.state = (await this.browserStateService.getBrowserGroupingComponentState()) || {};
if (this.state?.searchText) {
this.searchText = this.state.searchText;
} else if (params.searchText) {
this.searchText = params.searchText;
this.location.replaceState('vault');
this.location.replaceState("vault");
}
if (!this.syncService.syncInProgress) {
@ -160,7 +164,7 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
if (!this.hasLoadedAllCiphers) {
this.hasLoadedAllCiphers = !this.searchService.isSearchable(this.searchText);
}
this.deletedCount = this.allCiphers.filter(c => c.isDeleted).length;
this.deletedCount = this.allCiphers.filter((c) => c.isDeleted).length;
await this.search(null);
let favoriteCiphers: CipherView[] = null;
let noFolderCiphers: CipherView[] = null;
@ -168,7 +172,7 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
const collectionCounts = new Map<string, number>();
const typeCounts = new Map<CipherType, number>();
this.ciphers.forEach(c => {
this.ciphers.forEach((c) => {
if (c.isDeleted) {
return;
}
@ -199,7 +203,7 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
}
if (c.collectionIds != null) {
c.collectionIds.forEach(colId => {
c.collectionIds.forEach((colId) => {
if (collectionCounts.has(colId)) {
collectionCounts.set(colId, collectionCounts.get(colId) + 1);
} else {
@ -224,7 +228,11 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
const filterDeleted = (c: CipherView) => !c.isDeleted;
if (timeout == null) {
this.hasSearched = this.searchService.isSearchable(this.searchText);
this.ciphers = await this.searchService.searchCiphers(this.searchText, filterDeleted, this.allCiphers);
this.ciphers = await this.searchService.searchCiphers(
this.searchText,
filterDeleted,
this.allCiphers
);
return;
}
this.searchPending = true;
@ -233,7 +241,11 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
if (!this.hasLoadedAllCiphers && !this.hasSearched) {
await this.loadCiphers();
} else {
this.ciphers = await this.searchService.searchCiphers(this.searchText, filterDeleted, this.allCiphers);
this.ciphers = await this.searchService.searchCiphers(
this.searchText,
filterDeleted,
this.allCiphers
);
}
this.searchPending = false;
}, timeout);
@ -241,28 +253,28 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
async selectType(type: CipherType) {
super.selectType(type);
this.router.navigate(['/ciphers'], { queryParams: { type: type } });
this.router.navigate(["/ciphers"], { queryParams: { type: type } });
}
async selectFolder(folder: FolderView) {
super.selectFolder(folder);
this.router.navigate(['/ciphers'], { queryParams: { folderId: folder.id || 'none' } });
this.router.navigate(["/ciphers"], { queryParams: { folderId: folder.id || "none" } });
}
async selectCollection(collection: CollectionView) {
super.selectCollection(collection);
this.router.navigate(['/ciphers'], { queryParams: { collectionId: collection.id } });
this.router.navigate(["/ciphers"], { queryParams: { collectionId: collection.id } });
}
async selectTrash() {
super.selectTrash();
this.router.navigate(['/ciphers'], { queryParams: { deleted: true } });
this.router.navigate(["/ciphers"], { queryParams: { deleted: true } });
}
async selectCipher(cipher: CipherView) {
this.selectedTimeout = window.setTimeout(() => {
if (!this.preventSelected) {
this.router.navigate(['/view-cipher'], { queryParams: { cipherId: cipher.id } });
this.router.navigate(["/view-cipher"], { queryParams: { cipherId: cipher.id } });
}
this.preventSelected = false;
}, 200);
@ -285,16 +297,18 @@ export class GroupingsComponent extends BaseGroupingsComponent implements OnInit
}
async addCipher() {
this.router.navigate(['/add-cipher']);
this.router.navigate(["/add-cipher"]);
}
showSearching() {
return this.hasSearched || (!this.searchPending && this.searchService.isSearchable(this.searchText));
return (
this.hasSearched || (!this.searchPending && this.searchService.isSearchable(this.searchText))
);
}
closeOnEsc(e: KeyboardEvent) {
// If input not empty, use browser default behavior of clearing input instead
if (e.key === 'Escape' && (this.searchText == null || this.searchText === '')) {
if (e.key === "Escape" && (this.searchText == null || this.searchText === "")) {
BrowserApi.closePopup(window);
}
}

View File

@ -1,37 +1,46 @@
import { Component } from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { Component } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CollectionService } from 'jslib-common/abstractions/collection.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { OrganizationService } from 'jslib-common/abstractions/organization.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CollectionService } from "jslib-common/abstractions/collection.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { OrganizationService } from "jslib-common/abstractions/organization.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { ShareComponent as BaseShareComponent } from 'jslib-angular/components/share.component';
import { ShareComponent as BaseShareComponent } from "jslib-angular/components/share.component";
@Component({
selector: 'app-vault-share',
templateUrl: 'share.component.html',
selector: "app-vault-share",
templateUrl: "share.component.html",
})
export class ShareComponent extends BaseShareComponent {
constructor(collectionService: CollectionService, platformUtilsService: PlatformUtilsService,
i18nService: I18nService, logService: LogService,
cipherService: CipherService, private route: ActivatedRoute,
private router: Router, organizationService: OrganizationService) {
super(collectionService, platformUtilsService, i18nService, cipherService,
logService, organizationService);
constructor(
collectionService: CollectionService,
platformUtilsService: PlatformUtilsService,
i18nService: I18nService,
logService: LogService,
cipherService: CipherService,
private route: ActivatedRoute,
private router: Router,
organizationService: OrganizationService
) {
super(
collectionService,
platformUtilsService,
i18nService,
cipherService,
logService,
organizationService
);
}
async ngOnInit() {
this.onSharedCipher.subscribe(() => {
this.router.navigate(['view-cipher', { cipherId: this.cipherId }]);
this.router.navigate(["view-cipher", { cipherId: this.cipherId }]);
});
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
this.cipherId = params.cipherId;
await this.load();
});
@ -46,6 +55,9 @@ export class ShareComponent extends BaseShareComponent {
}
cancel() {
this.router.navigate(['/view-cipher'], { replaceUrl: true, queryParams: { cipherId: this.cipher.id } });
this.router.navigate(["/view-cipher"], {
replaceUrl: true,
queryParams: { cipherId: this.cipher.id },
});
}
}

View File

@ -1,49 +1,42 @@
import { Location } from '@angular/common';
import {
ChangeDetectorRef,
Component,
NgZone,
} from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { Location } from "@angular/common";
import { ChangeDetectorRef, Component, NgZone } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from 'rxjs/operators';
import { first } from "rxjs/operators";
import { ApiService } from 'jslib-common/abstractions/api.service';
import { AuditService } from 'jslib-common/abstractions/audit.service';
import { BroadcasterService } from 'jslib-common/abstractions/broadcaster.service';
import { CipherService } from 'jslib-common/abstractions/cipher.service';
import { CryptoService } from 'jslib-common/abstractions/crypto.service';
import { EventService } from 'jslib-common/abstractions/event.service';
import { I18nService } from 'jslib-common/abstractions/i18n.service';
import { LogService } from 'jslib-common/abstractions/log.service';
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PasswordRepromptService } from 'jslib-common/abstractions/passwordReprompt.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { TokenService } from 'jslib-common/abstractions/token.service';
import { TotpService } from 'jslib-common/abstractions/totp.service';
import { ApiService } from "jslib-common/abstractions/api.service";
import { AuditService } from "jslib-common/abstractions/audit.service";
import { BroadcasterService } from "jslib-common/abstractions/broadcaster.service";
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { CryptoService } from "jslib-common/abstractions/crypto.service";
import { EventService } from "jslib-common/abstractions/event.service";
import { I18nService } from "jslib-common/abstractions/i18n.service";
import { LogService } from "jslib-common/abstractions/log.service";
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PasswordRepromptService } from "jslib-common/abstractions/passwordReprompt.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { TokenService } from "jslib-common/abstractions/token.service";
import { TotpService } from "jslib-common/abstractions/totp.service";
import { Cipher } from 'jslib-common/models/domain/cipher';
import { LoginUriView } from 'jslib-common/models/view/loginUriView';
import { Cipher } from "jslib-common/models/domain/cipher";
import { LoginUriView } from "jslib-common/models/view/loginUriView";
import { CipherType } from 'jslib-common/enums/cipherType';
import { CipherType } from "jslib-common/enums/cipherType";
import { ViewComponent as BaseViewComponent } from 'jslib-angular/components/view.component';
import { ViewComponent as BaseViewComponent } from "jslib-angular/components/view.component";
import { BrowserApi } from '../../browser/browserApi';
import { BrowserApi } from "../../browser/browserApi";
import { AutofillService } from '../../services/abstractions/autofill.service';
import { StateService } from '../../services/abstractions/state.service';
import { AutofillService } from "../../services/abstractions/autofill.service";
import { StateService } from "../../services/abstractions/state.service";
import { PopupUtilsService } from '../services/popup-utils.service';
import { PopupUtilsService } from "../services/popup-utils.service";
const BroadcasterSubscriptionId = 'ChildViewComponent';
const BroadcasterSubscriptionId = "ChildViewComponent";
@Component({
selector: 'app-vault-view',
templateUrl: 'view.component.html',
selector: "app-vault-view",
templateUrl: "view.component.html",
})
export class ViewComponent extends BaseViewComponent {
showAttachments = true;
@ -53,26 +46,52 @@ export class ViewComponent extends BaseViewComponent {
inPopout = false;
cipherType = CipherType;
constructor(cipherService: CipherService, totpService: TotpService,
tokenService: TokenService, i18nService: I18nService,
cryptoService: CryptoService, platformUtilsService: PlatformUtilsService,
auditService: AuditService, private route: ActivatedRoute,
private router: Router, private location: Location,
broadcasterService: BroadcasterService, ngZone: NgZone,
changeDetectorRef: ChangeDetectorRef, stateService: StateService,
eventService: EventService, private autofillService: AutofillService,
private messagingService: MessagingService, private popupUtilsService: PopupUtilsService,
apiService: ApiService, passwordRepromptService: PasswordRepromptService,
logService: LogService) {
super(cipherService, totpService, tokenService, i18nService,
cryptoService, platformUtilsService, auditService, window,
broadcasterService, ngZone, changeDetectorRef, eventService,
apiService, passwordRepromptService, logService, stateService);
constructor(
cipherService: CipherService,
totpService: TotpService,
tokenService: TokenService,
i18nService: I18nService,
cryptoService: CryptoService,
platformUtilsService: PlatformUtilsService,
auditService: AuditService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
broadcasterService: BroadcasterService,
ngZone: NgZone,
changeDetectorRef: ChangeDetectorRef,
stateService: StateService,
eventService: EventService,
private autofillService: AutofillService,
private messagingService: MessagingService,
private popupUtilsService: PopupUtilsService,
apiService: ApiService,
passwordRepromptService: PasswordRepromptService,
logService: LogService
) {
super(
cipherService,
totpService,
tokenService,
i18nService,
cryptoService,
platformUtilsService,
auditService,
window,
broadcasterService,
ngZone,
changeDetectorRef,
eventService,
apiService,
passwordRepromptService,
logService,
stateService
);
}
ngOnInit() {
this.inPopout = this.popupUtilsService.inPopout(window);
this.route.queryParams.pipe(first()).subscribe(async params => {
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (params.cipherId) {
this.cipherId = params.cipherId;
} else {
@ -87,7 +106,7 @@ export class ViewComponent extends BaseViewComponent {
this.broadcasterService.subscribe(BroadcasterSubscriptionId, (message: any) => {
this.ngZone.run(async () => {
switch (message.command) {
case 'collectPageDetailsResponse':
case "collectPageDetailsResponse":
if (message.sender === BroadcasterSubscriptionId) {
this.pageDetails.push({
frameId: message.webExtSender.frameId,
@ -96,8 +115,8 @@ export class ViewComponent extends BaseViewComponent {
});
}
break;
case 'tabChanged':
case 'windowChanged':
case "tabChanged":
case "windowChanged":
if (this.loadPageDetailsTimeout != null) {
window.clearTimeout(this.loadPageDetailsTimeout);
}
@ -124,11 +143,11 @@ export class ViewComponent extends BaseViewComponent {
if (this.cipher.isDeleted) {
return false;
}
if (!await super.edit()) {
if (!(await super.edit())) {
return false;
}
this.router.navigate(['/edit-cipher'], { queryParams: { cipherId: this.cipher.id } });
this.router.navigate(["/edit-cipher"], { queryParams: { cipherId: this.cipher.id } });
return true;
}
@ -137,11 +156,11 @@ export class ViewComponent extends BaseViewComponent {
return false;
}
if (!await super.clone()) {
if (!(await super.clone())) {
return false;
}
this.router.navigate(['/clone-cipher'], {
this.router.navigate(["/clone-cipher"], {
queryParams: {
cloneMode: true,
cipherId: this.cipher.id,
@ -151,12 +170,15 @@ export class ViewComponent extends BaseViewComponent {
}
async share() {
if (!await super.share()) {
if (!(await super.share())) {
return false;
}
if (this.cipher.organizationId == null) {
this.router.navigate(['/share-cipher'], { replaceUrl: true, queryParams: { cipherId: this.cipher.id } });
this.router.navigate(["/share-cipher"], {
replaceUrl: true,
queryParams: { cipherId: this.cipher.id },
});
}
return true;
}
@ -164,8 +186,7 @@ export class ViewComponent extends BaseViewComponent {
async fillCipher() {
const didAutofill = await this.doAutofill();
if (didAutofill) {
this.platformUtilsService.showToast('success', null,
this.i18nService.t('autoFillSuccess'));
this.platformUtilsService.showToast("success", null, this.i18nService.t("autoFillSuccess"));
}
}
@ -174,15 +195,18 @@ export class ViewComponent extends BaseViewComponent {
if (didAutofill) {
if (this.tab == null) {
throw new Error('No tab found.');
throw new Error("No tab found.");
}
if (this.cipher.login.uris == null) {
this.cipher.login.uris = [];
} else {
if (this.cipher.login.uris.some(uri => uri.uri === this.tab.url)) {
this.platformUtilsService.showToast('success', null,
this.i18nService.t('autoFillSuccessAndSavedUri'));
if (this.cipher.login.uris.some((uri) => uri.uri === this.tab.url)) {
this.platformUtilsService.showToast(
"success",
null,
this.i18nService.t("autoFillSuccessAndSavedUri")
);
return;
}
}
@ -194,12 +218,14 @@ export class ViewComponent extends BaseViewComponent {
try {
const cipher: Cipher = await this.cipherService.encrypt(this.cipher);
await this.cipherService.saveWithServer(cipher);
this.platformUtilsService.showToast('success', null,
this.i18nService.t('autoFillSuccessAndSavedUri'));
this.messagingService.send('editedCipher');
this.platformUtilsService.showToast(
"success",
null,
this.i18nService.t("autoFillSuccessAndSavedUri")
);
this.messagingService.send("editedCipher");
} catch {
this.platformUtilsService.showToast('error', null,
this.i18nService.t('unexpectedError'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("unexpectedError"));
}
}
}
@ -234,20 +260,19 @@ export class ViewComponent extends BaseViewComponent {
return;
}
BrowserApi.tabSendMessage(this.tab, {
command: 'collectPageDetails',
command: "collectPageDetails",
tab: this.tab,
sender: BroadcasterSubscriptionId,
});
}
private async doAutofill() {
if (!await this.promptPassword()) {
if (!(await this.promptPassword())) {
return false;
}
if (this.pageDetails == null || this.pageDetails.length === 0) {
this.platformUtilsService.showToast('error', null,
this.i18nService.t('autofillError'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("autofillError"));
return false;
}
@ -262,8 +287,7 @@ export class ViewComponent extends BaseViewComponent {
this.platformUtilsService.copyToClipboard(this.totpCode, { window: window });
}
} catch {
this.platformUtilsService.showToast('error', null,
this.i18nService.t('autofillError'));
this.platformUtilsService.showToast("error", null, this.i18nService.t("autofillError"));
this.changeDetectorRef.detectChanges();
return false;
}

View File

@ -1,20 +1,33 @@
import { StateService as BaseStateServiceAbstraction } from 'jslib-common/abstractions/state.service';
import { StateService as BaseStateServiceAbstraction } from "jslib-common/abstractions/state.service";
import { StorageOptions } from 'jslib-common/models/domain/storageOptions';
import { Account } from 'src/models/account';
import { BrowserComponentState } from 'src/models/browserComponentState';
import { BrowserGroupingsComponentState } from 'src/models/browserGroupingsComponentState';
import { BrowserSendComponentState } from 'src/models/browserSendComponentState';
import { StorageOptions } from "jslib-common/models/domain/storageOptions";
import { Account } from "src/models/account";
import { BrowserComponentState } from "src/models/browserComponentState";
import { BrowserGroupingsComponentState } from "src/models/browserGroupingsComponentState";
import { BrowserSendComponentState } from "src/models/browserSendComponentState";
export abstract class StateService extends BaseStateServiceAbstraction<Account> {
getBrowserGroupingComponentState: (options?: StorageOptions) => Promise<BrowserGroupingsComponentState>;
setBrowserGroupingComponentState: (value: BrowserGroupingsComponentState, options?: StorageOptions) => Promise<void>;
getBrowserGroupingComponentState: (
options?: StorageOptions
) => Promise<BrowserGroupingsComponentState>;
setBrowserGroupingComponentState: (
value: BrowserGroupingsComponentState,
options?: StorageOptions
) => Promise<void>;
getBrowserCipherComponentState: (options?: StorageOptions) => Promise<BrowserComponentState>;
setBrowserCipherComponentState: (value: BrowserComponentState, options?: StorageOptions) => Promise<void>;
setBrowserCipherComponentState: (
value: BrowserComponentState,
options?: StorageOptions
) => Promise<void>;
getBrowserSendComponentState: (options?: StorageOptions) => Promise<BrowserSendComponentState>;
setBrowserSendComponentState: (value: BrowserSendComponentState, options?: StorageOptions) => Promise<void>;
setBrowserSendComponentState: (
value: BrowserSendComponentState,
options?: StorageOptions
) => Promise<void>;
getBrowserSendTypeComponentState: (options?: StorageOptions) => Promise<BrowserComponentState>;
setBrowserSendTypeComponentState: (value: BrowserComponentState, options?: StorageOptions) => Promise<void>;
setBrowserSendTypeComponentState: (
value: BrowserComponentState,
options?: StorageOptions
) => Promise<void>;
}

View File

@ -1,10 +1,10 @@
import { KeySuffixOptions } from 'jslib-common/enums/keySuffixOptions';
import { KeySuffixOptions } from "jslib-common/enums/keySuffixOptions";
import { CryptoService } from 'jslib-common/services/crypto.service';
import { CryptoService } from "jslib-common/services/crypto.service";
export class BrowserCryptoService extends CryptoService {
protected async retrieveKeyFromStorage(keySuffix: KeySuffixOptions) {
if (keySuffix === 'biometric') {
if (keySuffix === "biometric") {
await this.platformUtilService.authenticateBiometric();
return (await this.getKey())?.keyB64;
}

View File

@ -1,44 +1,56 @@
import { BrowserApi } from '../browser/browserApi';
import { SafariApp } from '../browser/safariApp';
import { BrowserApi } from "../browser/browserApi";
import { SafariApp } from "../browser/safariApp";
import { DeviceType } from 'jslib-common/enums/deviceType';
import { ThemeType } from 'jslib-common/enums/themeType';
import { DeviceType } from "jslib-common/enums/deviceType";
import { ThemeType } from "jslib-common/enums/themeType";
import { MessagingService } from 'jslib-common/abstractions/messaging.service';
import { PlatformUtilsService } from 'jslib-common/abstractions/platformUtils.service';
import { StateService } from '../services/abstractions/state.service';
import { MessagingService } from "jslib-common/abstractions/messaging.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { StateService } from "../services/abstractions/state.service";
const DialogPromiseExpiration = 600000; // 10 minutes
export default class BrowserPlatformUtilsService implements PlatformUtilsService {
identityClientId: string = 'browser';
identityClientId: string = "browser";
private showDialogResolves = new Map<number, { resolve: (value: boolean) => void, date: Date }>();
private passwordDialogResolves = new Map<number, { tryResolve: (canceled: boolean, password: string) => Promise<boolean>, date: Date }>();
private showDialogResolves = new Map<number, { resolve: (value: boolean) => void; date: Date }>();
private passwordDialogResolves = new Map<
number,
{ tryResolve: (canceled: boolean, password: string) => Promise<boolean>; date: Date }
>();
private deviceCache: DeviceType = null;
private prefersColorSchemeDark = window.matchMedia('(prefers-color-scheme: dark)');
private prefersColorSchemeDark = window.matchMedia("(prefers-color-scheme: dark)");
constructor(private messagingService: MessagingService, private stateService: StateService,
constructor(
private messagingService: MessagingService,
private stateService: StateService,
private clipboardWriteCallback: (clipboardValue: string, clearMs: number) => void,
private biometricCallback: () => Promise<boolean>) { }
private biometricCallback: () => Promise<boolean>
) {}
getDevice(): DeviceType {
if (this.deviceCache) {
return this.deviceCache;
}
if (navigator.userAgent.indexOf(' Firefox/') !== -1 || navigator.userAgent.indexOf(' Gecko/') !== -1) {
if (
navigator.userAgent.indexOf(" Firefox/") !== -1 ||
navigator.userAgent.indexOf(" Gecko/") !== -1
) {
this.deviceCache = DeviceType.FirefoxExtension;
} else if ((!!(window as any).opr && !!opr.addons) || !!(window as any).opera ||
navigator.userAgent.indexOf(' OPR/') >= 0) {
} else if (
(!!(window as any).opr && !!opr.addons) ||
!!(window as any).opera ||
navigator.userAgent.indexOf(" OPR/") >= 0
) {
this.deviceCache = DeviceType.OperaExtension;
} else if (navigator.userAgent.indexOf(' Edg/') !== -1) {
} else if (navigator.userAgent.indexOf(" Edg/") !== -1) {
this.deviceCache = DeviceType.EdgeExtension;
} else if (navigator.userAgent.indexOf(' Vivaldi/') !== -1) {
} else if (navigator.userAgent.indexOf(" Vivaldi/") !== -1) {
this.deviceCache = DeviceType.VivaldiExtension;
} else if ((window as any).chrome && navigator.userAgent.indexOf(' Chrome/') !== -1) {
} else if ((window as any).chrome && navigator.userAgent.indexOf(" Chrome/") !== -1) {
this.deviceCache = DeviceType.ChromeExtension;
} else if (navigator.userAgent.indexOf(' Safari/') !== -1) {
} else if (navigator.userAgent.indexOf(" Safari/") !== -1) {
this.deviceCache = DeviceType.SafariExtension;
}
@ -47,7 +59,7 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
getDeviceString(): string {
const device = DeviceType[this.getDevice()].toLowerCase();
return device.replace('extension', '');
return device.replace("extension", "");
}
isFirefox(): boolean {
@ -92,12 +104,13 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
}
const sidebarView = this.sidebarViewName();
const sidebarOpen = sidebarView != null && chrome.extension.getViews({ type: sidebarView }).length > 0;
const sidebarOpen =
sidebarView != null && chrome.extension.getViews({ type: sidebarView }).length > 0;
if (sidebarOpen) {
return true;
}
const tabOpen = chrome.extension.getViews({ type: 'tab' }).length > 0;
const tabOpen = chrome.extension.getViews({ type: "tab" }).length > 0;
return tabOpen;
}
@ -118,16 +131,20 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
}
supportsWebAuthn(win: Window): boolean {
return (typeof (PublicKeyCredential) !== 'undefined');
return typeof PublicKeyCredential !== "undefined";
}
supportsDuo(): boolean {
return true;
}
showToast(type: 'error' | 'success' | 'warning' | 'info', title: string, text: string | string[],
options?: any): void {
this.messagingService.send('showToast', {
showToast(
type: "error" | "success" | "warning" | "info",
title: string,
text: string | string[],
options?: any
): void {
this.messagingService.send("showToast", {
text: text,
title: title,
type: type,
@ -135,10 +152,16 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
});
}
showDialog(body: string, title?: string, confirmText?: string, cancelText?: string, type?: string,
bodyIsHtml: boolean = false) {
showDialog(
body: string,
title?: string,
confirmText?: string,
cancelText?: string,
type?: string,
bodyIsHtml: boolean = false
) {
const dialogId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
this.messagingService.send('showDialog', {
this.messagingService.send("showDialog", {
text: bodyIsHtml ? null : body,
html: bodyIsHtml ? body : null,
title: title,
@ -147,13 +170,13 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
type: type,
dialogId: dialogId,
});
return new Promise<boolean>(resolve => {
return new Promise<boolean>((resolve) => {
this.showDialogResolves.set(dialogId, { resolve: resolve, date: new Date() });
});
}
isDev(): boolean {
return process.env.ENV === 'development';
return process.env.ENV === "development";
}
isSelfHost(): boolean {
@ -173,12 +196,16 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
const clearMs: number = options && options.clearMs ? options.clearMs : null;
if (this.isSafari()) {
SafariApp.sendMessageToApp('copyToClipboard', text).then(() => {
SafariApp.sendMessageToApp("copyToClipboard", text).then(() => {
if (!clearing && this.clipboardWriteCallback != null) {
this.clipboardWriteCallback(text, clearMs);
}
});
} else if (this.isFirefox() && (win as any).navigator.clipboard && (win as any).navigator.clipboard.writeText) {
} else if (
this.isFirefox() &&
(win as any).navigator.clipboard &&
(win as any).navigator.clipboard.writeText
) {
(win as any).navigator.clipboard.writeText(text).then(() => {
if (!clearing && this.clipboardWriteCallback != null) {
this.clipboardWriteCallback(text, clearMs);
@ -186,30 +213,30 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
});
} else if ((win as any).clipboardData && (win as any).clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
(win as any).clipboardData.setData('Text', text);
(win as any).clipboardData.setData("Text", text);
if (!clearing && this.clipboardWriteCallback != null) {
this.clipboardWriteCallback(text, clearMs);
}
} else if (doc.queryCommandSupported && doc.queryCommandSupported('copy')) {
if (this.isChrome() && text === '') {
text = '\u0000';
} else if (doc.queryCommandSupported && doc.queryCommandSupported("copy")) {
if (this.isChrome() && text === "") {
text = "\u0000";
}
const textarea = doc.createElement('textarea');
textarea.textContent = text == null || text === '' ? ' ' : text;
const textarea = doc.createElement("textarea");
textarea.textContent = text == null || text === "" ? " " : text;
// Prevent scrolling to bottom of page in MS Edge.
textarea.style.position = 'fixed';
textarea.style.position = "fixed";
doc.body.appendChild(textarea);
textarea.select();
try {
// Security exception may be thrown by some browsers.
if (doc.execCommand('copy') && !clearing && this.clipboardWriteCallback != null) {
if (doc.execCommand("copy") && !clearing && this.clipboardWriteCallback != null) {
this.clipboardWriteCallback(text, clearMs);
}
} catch (e) {
// tslint:disable-next-line
console.warn('Copy to clipboard failed.', e);
console.warn("Copy to clipboard failed.", e);
} finally {
doc.body.removeChild(textarea);
}
@ -227,23 +254,27 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
}
if (this.isSafari()) {
return await SafariApp.sendMessageToApp('readFromClipboard');
} else if (this.isFirefox() && (win as any).navigator.clipboard && (win as any).navigator.clipboard.readText) {
return await SafariApp.sendMessageToApp("readFromClipboard");
} else if (
this.isFirefox() &&
(win as any).navigator.clipboard &&
(win as any).navigator.clipboard.readText
) {
return await (win as any).navigator.clipboard.readText();
} else if (doc.queryCommandSupported && doc.queryCommandSupported('paste')) {
const textarea = doc.createElement('textarea');
} else if (doc.queryCommandSupported && doc.queryCommandSupported("paste")) {
const textarea = doc.createElement("textarea");
// Prevent scrolling to bottom of page in MS Edge.
textarea.style.position = 'fixed';
textarea.style.position = "fixed";
doc.body.appendChild(textarea);
textarea.focus();
try {
// Security exception may be thrown by some browsers.
if (doc.execCommand('paste')) {
if (doc.execCommand("paste")) {
return textarea.value;
}
} catch (e) {
// tslint:disable-next-line
console.warn('Read from clipboard failed.', e);
console.warn("Read from clipboard failed.", e);
} finally {
doc.body.removeChild(textarea);
}
@ -267,7 +298,11 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
});
}
async resolvePasswordDialogPromise(dialogId: number, canceled: boolean, password: string): Promise<boolean> {
async resolvePasswordDialogPromise(
dialogId: number,
canceled: boolean,
password: string
): Promise<boolean> {
let result = false;
if (this.passwordDialogResolves.has(dialogId)) {
const resolveObj = this.passwordDialogResolves.get(dialogId);
@ -290,12 +325,12 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
async supportsBiometric() {
const platformInfo = await BrowserApi.getPlatformInfo();
if (platformInfo.os === 'android') {
if (platformInfo.os === "android") {
return false;
}
if (this.isFirefox()) {
return parseInt((await browser.runtime.getBrowserInfo()).version.split('.')[0], 10) >= 87;
return parseInt((await browser.runtime.getBrowserInfo()).version.split(".")[0], 10) >= 87;
}
return true;
@ -307,9 +342,9 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
sidebarViewName(): string {
if ((window as any).chrome.sidebarAction && this.isFirefox()) {
return 'sidebar';
} else if (this.isOpera() && (typeof opr !== 'undefined') && opr.sidebarAction) {
return 'sidebar_panel';
return "sidebar";
} else if (this.isOpera() && typeof opr !== "undefined" && opr.sidebarAction) {
return "sidebar_panel";
}
return null;
@ -323,14 +358,14 @@ export default class BrowserPlatformUtilsService implements PlatformUtilsService
return Promise.resolve(this.prefersColorSchemeDark.matches ? ThemeType.Dark : ThemeType.Light);
}
onDefaultSystemThemeChange(callback: ((theme: ThemeType.Light | ThemeType.Dark) => unknown)) {
this.prefersColorSchemeDark.addEventListener('change', ({ matches }) => {
onDefaultSystemThemeChange(callback: (theme: ThemeType.Light | ThemeType.Dark) => unknown) {
this.prefersColorSchemeDark.addEventListener("change", ({ matches }) => {
callback(matches ? ThemeType.Dark : ThemeType.Light);
});
}
async getEffectiveTheme() {
const theme = await this.stateService.getTheme() as ThemeType;
const theme = (await this.stateService.getTheme()) as ThemeType;
if (theme == null || theme === ThemeType.System) {
return this.getDefaultSystemTheme();
} else {

View File

@ -1,4 +1,4 @@
import { StorageService } from 'jslib-common/abstractions/storage.service';
import { StorageService } from "jslib-common/abstractions/storage.service";
export default class BrowserStorageService implements StorageService {
private chromeStorageApi: any;
@ -8,7 +8,7 @@ export default class BrowserStorageService implements StorageService {
}
async get<T>(key: string): Promise<T> {
return new Promise(resolve => {
return new Promise((resolve) => {
this.chromeStorageApi.get(key, (obj: any) => {
if (obj != null && obj[key] != null) {
resolve(obj[key] as T);
@ -20,7 +20,7 @@ export default class BrowserStorageService implements StorageService {
}
async has(key: string): Promise<boolean> {
return await this.get(key) != null;
return (await this.get(key)) != null;
}
async save(key: string, obj: any): Promise<any> {
@ -34,7 +34,7 @@ export default class BrowserStorageService implements StorageService {
}
const keyedObj = { [key]: obj };
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
this.chromeStorageApi.set(keyedObj, () => {
resolve();
});
@ -42,7 +42,7 @@ export default class BrowserStorageService implements StorageService {
}
async remove(key: string): Promise<any> {
return new Promise<void>(resolve => {
return new Promise<void>((resolve) => {
this.chromeStorageApi.remove(key, () => {
resolve();
});

View File

@ -1,52 +1,75 @@
import { StorageOptions } from 'jslib-common/models/domain/storageOptions';
import { StateService as BaseStateService } from 'jslib-common/services/state.service';
import { Account } from 'src/models/account';
import { BrowserComponentState } from '../models/browserComponentState';
import { BrowserGroupingsComponentState } from '../models/browserGroupingsComponentState';
import { BrowserSendComponentState } from '../models/browserSendComponentState';
import { StateService as StateServiceAbstraction } from './abstractions/state.service';
import { StorageOptions } from "jslib-common/models/domain/storageOptions";
import { StateService as BaseStateService } from "jslib-common/services/state.service";
import { Account } from "src/models/account";
import { BrowserComponentState } from "../models/browserComponentState";
import { BrowserGroupingsComponentState } from "../models/browserGroupingsComponentState";
import { BrowserSendComponentState } from "../models/browserSendComponentState";
import { StateService as StateServiceAbstraction } from "./abstractions/state.service";
export class StateService extends BaseStateService<Account> implements StateServiceAbstraction {
async getBrowserGroupingComponentState(options?: StorageOptions): Promise<BrowserGroupingsComponentState> {
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))?.groupings;
async getBrowserGroupingComponentState(
options?: StorageOptions
): Promise<BrowserGroupingsComponentState> {
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))
?.groupings;
}
async setBrowserGroupingComponentState(value: BrowserGroupingsComponentState, options?: StorageOptions): Promise<void> {
const account = await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions));
async setBrowserGroupingComponentState(
value: BrowserGroupingsComponentState,
options?: StorageOptions
): Promise<void> {
const account = await this.getAccount(
this.reconcileOptions(options, this.defaultInMemoryOptions)
);
account.groupings = value;
await this.saveAccount(account, this.reconcileOptions(options, this.defaultInMemoryOptions));
}
async getBrowserCipherComponentState(options?: StorageOptions): Promise<BrowserComponentState> {
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))?.ciphers;
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))
?.ciphers;
}
async setBrowserCipherComponentState(value: BrowserComponentState, options?: StorageOptions): Promise<void> {
const account = await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions));
async setBrowserCipherComponentState(
value: BrowserComponentState,
options?: StorageOptions
): Promise<void> {
const account = await this.getAccount(
this.reconcileOptions(options, this.defaultInMemoryOptions)
);
account.ciphers = value;
await this.saveAccount(account, this.reconcileOptions(options, this.defaultInMemoryOptions));
}
async getBrowserSendComponentState(options?: StorageOptions): Promise<BrowserSendComponentState> {
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))?.send;
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))
?.send;
}
async setBrowserSendComponentState(value: BrowserSendComponentState, options?: StorageOptions): Promise<void> {
const account = await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions));
async setBrowserSendComponentState(
value: BrowserSendComponentState,
options?: StorageOptions
): Promise<void> {
const account = await this.getAccount(
this.reconcileOptions(options, this.defaultInMemoryOptions)
);
account.send = value;
await this.saveAccount(account, this.reconcileOptions(options, this.defaultInMemoryOptions));
}
async getBrowserSendTypeComponentState(options?: StorageOptions): Promise<BrowserComponentState> {
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))?.sendType;
return (await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions)))
?.sendType;
}
async setBrowserSendTypeComponentState(value: BrowserComponentState, options?: StorageOptions): Promise<void> {
const account = await this.getAccount(this.reconcileOptions(options, this.defaultInMemoryOptions));
async setBrowserSendTypeComponentState(
value: BrowserComponentState,
options?: StorageOptions
): Promise<void> {
const account = await this.getAccount(
this.reconcileOptions(options, this.defaultInMemoryOptions)
);
account.sendType = value;
await this.saveAccount(account, this.reconcileOptions(options, this.defaultInMemoryOptions));
}
}