bitwarden-estensione-browser/libs/common/src/services/notifications.service.ts

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

264 lines
9.3 KiB
TypeScript
Raw Normal View History

2020-01-09 23:27:07 +01:00
import * as signalR from "@microsoft/signalr";
import * as signalRMsgPack from "@microsoft/signalr-protocol-msgpack";
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
import { firstValueFrom, Subscription } from "rxjs";
2018-08-20 19:45:32 +02:00
Auth - PM-7392 & PM-7436 - Token Service - Desktop - Add disk fallback for secure storage failures (#8913) * PM-7392 - EncryptSvc - add new method for detecting if a simple string is an enc string. * PM-7392 - TokenSvc - add checks when setting and retrieving the access token to improve handling around the access token encryption. * PM-7392 - (1) Clean up token svc (2) export access token key type for use in tests. * PM-7392 - Get token svc tests passing; WIP more tests to come for new scenarios. * PM-7392 - Access token secure storage to disk fallback WIP but mostly functional besides weird logout behavior. * PM-7392 - Clean up unnecessary comment * PM-7392 - TokenSvc - refresh token disk storage fallback * PM-7392 - Fix token service tests in prep for adding tests for new scenarios. * PM-7392 - TokenSvc tests - Test new setRefreshToken scenarios * PM-7392 - TokenSvc - getRefreshToken should return null or a value - not undefined. * PM-7392 - Fix test name. * PM-7392 - TokenSvc tests - clean up test names that reference removed refresh token migrated flag. * PM-7392 - getRefreshToken tests done. * PM-7392 - Fix error quote * PM-7392 - TokenSvc tests - setAccessToken new scenarios tested. * PM-7392 - TokenSvc - getAccessToken - if secure storage errors add error to log. * PM-7392 - TokenSvc tests - getAccessToken - all new scenarios tested * PM-7392 - EncryptSvc - test new stringIsEncString method * PM-7392 - Main.ts - fix circ dep issue. * PM-7392 - Main.ts - remove comment. * PM-7392 - Don't re-invent the wheel and simply use existing isSerializedEncString static method. * PM-7392 - Enc String - (1) Add handling for Nan in parseEncryptedString (2) Added null handling to isSerializedEncString. (3) Plan to remove encrypt service implementation Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Remove encrypt service method Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Actually fix circ dep issues with Justin. Ty! Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - TokenSvc - update to use EncString instead of EncryptSvc + fix tests. * PM-7392 - TokenSvc - (1) Remove test code (2) Refactor decryptAccessToken method to accept access token key and error on failure to pass required decryption key to method. * PM-7392 - Per PR feedback and discussion, do not log the user out if hte refresh token cannot be found. This will allow users to continue to use the app until their access token expires and we will error on trying to refresh it. The app will then still work on a fresh login for 55 min. * PM-7392 - API service - update doAuthRefresh error to clarify which token cannot be refreshed. * PM-7392 - Fix SetRefreshToken case where a null input would incorrectly trigger a fallback to disk. * PM-7392 - If the access token cannot be refreshed due to a missing refresh token or API keys, then surface an error to the user and log it so it isn't a silent failure + we get a log. * PM-7392 - Fix CLI build errors * PM-7392 - Per PR feedback, add missing tests (thank you Jake for writing these!) Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-7392 - Per PR feedback, update incorrect comment from 3 releases to 3 months. * PM-7392 - Per PR feedback, remove links. * PM-7392 - Per PR feedback, move tests to existing describe. * PM-7392 - Per PR feedback, adjust all test names to match naming convention. * PM-7392 - ApiService - refreshIdentityToken - log error before swallowing it so we have a record of it. * PM-7392 - Fix copy for errorRefreshingAccessToken * PM-7392 - Per PR feedback, move error handling toast responsibility to client specific app component logic reached via messaging. * PM-7392 - Swap logout reason from enum to type. * PM-7392 - ApiService - Stop using messaging to trigger toast to let user know about refresh access token errors; replace with client specific callback logic. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * PM-7392 - Per PR feedback, adjust enc string changes and tests. * PM-7392 - Rename file to be type from enum * PM-7392 - ToastService - we need to await the activeToast.onHidden observable so return the activeToast from the showToast. * PM-7392 - Desktop AppComp - cleanup messaging * PM-7392 - Move Logout reason custom type to auth/common * PM-7392 - WIP - Enhancing logout callback to consider the logout reason + move show toast logic into logout callback * PM-7392 - Logout callback should simply pass along the LogoutReason instead of handling it - let each client's message listener handle it. * PM-7392 - More replacements of expired with logoutReason * PM-7392 - More expired to logoutReason replacements * PM-7392 - Build new handlers for displaying the logout reason for desktop & web. * PM-7392 - Revert ToastService changes * PM-7392 - TokenSvc - Replace messageSender with logout callback per PR feedback. * PM-7392 - Desktop App comp - replace toast usage with simple dialog to guarantee users will see the reason for them being logged out. * PM-7392 - Web app comp - fix issue * PM-7392 - Desktop App comp - don't show cancel btn on simple dialogs. * PM-7392 - Desktop App comp - Don't open n simple dialogs. * PM-7392 - Fix browser build * PM-7392 - Remove logout reason from CLI as each logout call handles messaging on its own. * PM-7392 - Previously, if a security stamp was invalid, the session was marked as expired. Restore that functionality. * PM-7392 - Update sync service logoutCallback to include optional user id. * PM-7392 - Clean up web app comp * PM-7392 - Web - app comp - only handle actually possible web logout scenarios. * PM-7392 - Browser Popup app comp - restore done logging out message functionality + add new default logout message * PM-7392 - Add optional user id to logout callbacks. * PM-7392 - Main.background.ts - add clarifying comment. * PM-7392 - Per feedback, use danger simple dialog type for error. * PM-7392 - Browser Popup - add comment clarifying expectation of seeing toasts. * PM-7392 - Consolidate invalidSecurityStamp error handling * PM-7392 - Per PR feedback, REFRESH_ACCESS_TOKEN_ERROR_CALLBACK can be completely sync. + Refactor to method in main.background. * PM-7392 - Per PR feedback, use a named callback for refreshAccessTokenErrorCallback in CLI * PM-7392 - Add TODO * PM-7392 - Re-apply bw.ts changes to new service-container. * PM-7392 - TokenSvc - tweak error message. * PM-7392 - Fix test * PM-7392 - Clean up merge conflict where I duplicated dependencies. * PM-7392 - Per discussion with product, change default logout toast to be info * PM-7392 - After merge, add new logout reason to sync service. * PM-7392 - Remove default logout message per discussion with product since it isn't really visible on desktop or browser. * PM-7392 - address PR feedback. --------- Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2024-06-03 18:36:45 +02:00
import { LogoutReason } from "@bitwarden/auth/common";
import { ApiService } from "../abstractions/api.service";
2018-08-20 19:45:32 +02:00
import { NotificationsService as NotificationsServiceAbstraction } from "../abstractions/notifications.service";
Auth/ps 2298 reorg auth (#4564) * Move auth service factories to Auth team * Move authentication componenets to Auth team * Move auth guard services to Auth team * Move Duo content script to Auth team * Move auth CLI commands to Auth team * Move Desktop Account components to Auth Team * Move Desktop guards to Auth team * Move two-factor provider images to Auth team * Move web Accounts components to Auth Team * Move web settings components to Auth Team * Move web two factor images to Auth Team * Fix missed import changes for Auth Team * Fix Linting errors * Fix missed CLI imports * Fix missed Desktop imports * Revert images move * Fix missed imports in Web * Move angular lib components to Auth Team * Move angular auth guards to Auth team * Move strategy specs to Auth team * Update .eslintignore for new paths * Move lib common abstractions to Auth team * Move services to Auth team * Move common lib enums to Auth team * Move webauthn iframe to Auth team * Move lib common domain models to Auth team * Move common lib requests to Auth team * Move response models to Auth team * Clean up whitelist * Move bit web components to Auth team * Move SSO and SCIM files to Auth team * Revert move SCIM to Auth team SCIM belongs to Admin Console team * Move captcha to Auth team * Move key connector to Auth team * Move emergency access to auth team * Delete extra file * linter fixes * Move kdf config to auth team * Fix whitelist * Fix duo autoformat * Complete two factor provider request move * Fix whitelist names * Fix login capitalization * Revert hint dependency reordering * Revert hint dependency reordering * Revert hint component This components is being picked up as a move between clients * Move web hint component to Auth team * Move new files to auth team * Fix desktop build * Fix browser build
2023-02-06 22:53:37 +01:00
import { AuthService } from "../auth/abstractions/auth.service";
import { AuthenticationStatus } from "../auth/enums/authentication-status";
[AC-1266] Enums filename conventions (#5140) * refactor: update clientType enum * refactor: update deviceType filename * refactor: update encryptedExportType filename * refactor: update encryptionType filename * refactor: update eventType filename * refactor: update fieldType filename * refactor: update fileUploadType filename * refactor: update hashPurpose filename * refactor: update htmlStorageLocation filename * refactor: update kdfType filename * refactor: update keySuffixOptions filename * refactor: update linkedIdType filename * refactor: update logLevelType filename * refactor: update nativeMessagingVersion filename * refactor: update notificationType filename * refactor: update productType filename * refactor: update secureNoteType filename * refactor: update stateVersion filename * refactor: update storageLocation filename * refactor: update themeType filename * refactor: update uriMatchType filename * fix: update kdfType classes missed in initial pass, refs AC-1266 * fix: missing import update for device-type * refactor: add barrel file for enums and update pathed import statements, refs AC-1266 * fix: incorrect import statements for web, refs AC-1266 * fix: missed import statement updates (browser), refs AC-1266 * fix: missed import statement changes (cli), refs AC-1266 * fix: missed import statement changes (desktop), refs AC-1266 * fix: prettier, refs AC-1266 * refactor: (libs) update relative paths to use barrel file, refs AC-1266 * fix: missed find/replace import statements for SecureNoteType, refs AC-1266 * refactor: apply .enum suffix to enums folder and modify leftover relative paths, refs AC-1266 * fix: find/replace errors for native-messaging-version, refs AC-1266
2023-04-05 05:42:21 +02:00
import { NotificationType } from "../enums";
2018-08-20 22:01:26 +02:00
import {
NotificationResponse,
SyncCipherNotification,
SyncFolderNotification,
SyncSendNotification,
} from "../models/response/notification.response";
import { AppIdService } from "../platform/abstractions/app-id.service";
import { EnvironmentService } from "../platform/abstractions/environment.service";
import { LogService } from "../platform/abstractions/log.service";
import { MessagingService } from "../platform/abstractions/messaging.service";
import { StateService } from "../platform/abstractions/state.service";
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
import { ScheduledTaskNames } from "../platform/scheduling/scheduled-task-name.enum";
import { TaskSchedulerService } from "../platform/scheduling/task-scheduler.service";
import { SyncService } from "../vault/abstractions/sync/sync.service.abstraction";
2018-08-20 19:45:32 +02:00
export class NotificationsService implements NotificationsServiceAbstraction {
private signalrConnection: signalR.HubConnection;
private url: string;
private connected = false;
private inited = false;
2018-08-23 03:09:58 +02:00
private inactive = false;
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
private reconnectTimerSubscription: Subscription;
private isSyncingOnReconnect = true;
2021-12-16 13:36:21 +01:00
[Account Switching] [Feature] Allow clients to store data for more than one user (#491) * [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commit e8970725be472386358c1e2f06f53663c4979e0e. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
constructor(
private logService: LogService,
[Account Switching] [Feature] Allow clients to store data for more than one user (#491) * [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commit e8970725be472386358c1e2f06f53663c4979e0e. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
private syncService: SyncService,
private appIdService: AppIdService,
private apiService: ApiService,
private environmentService: EnvironmentService,
Auth - PM-7392 & PM-7436 - Token Service - Desktop - Add disk fallback for secure storage failures (#8913) * PM-7392 - EncryptSvc - add new method for detecting if a simple string is an enc string. * PM-7392 - TokenSvc - add checks when setting and retrieving the access token to improve handling around the access token encryption. * PM-7392 - (1) Clean up token svc (2) export access token key type for use in tests. * PM-7392 - Get token svc tests passing; WIP more tests to come for new scenarios. * PM-7392 - Access token secure storage to disk fallback WIP but mostly functional besides weird logout behavior. * PM-7392 - Clean up unnecessary comment * PM-7392 - TokenSvc - refresh token disk storage fallback * PM-7392 - Fix token service tests in prep for adding tests for new scenarios. * PM-7392 - TokenSvc tests - Test new setRefreshToken scenarios * PM-7392 - TokenSvc - getRefreshToken should return null or a value - not undefined. * PM-7392 - Fix test name. * PM-7392 - TokenSvc tests - clean up test names that reference removed refresh token migrated flag. * PM-7392 - getRefreshToken tests done. * PM-7392 - Fix error quote * PM-7392 - TokenSvc tests - setAccessToken new scenarios tested. * PM-7392 - TokenSvc - getAccessToken - if secure storage errors add error to log. * PM-7392 - TokenSvc tests - getAccessToken - all new scenarios tested * PM-7392 - EncryptSvc - test new stringIsEncString method * PM-7392 - Main.ts - fix circ dep issue. * PM-7392 - Main.ts - remove comment. * PM-7392 - Don't re-invent the wheel and simply use existing isSerializedEncString static method. * PM-7392 - Enc String - (1) Add handling for Nan in parseEncryptedString (2) Added null handling to isSerializedEncString. (3) Plan to remove encrypt service implementation Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Remove encrypt service method Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Actually fix circ dep issues with Justin. Ty! Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - TokenSvc - update to use EncString instead of EncryptSvc + fix tests. * PM-7392 - TokenSvc - (1) Remove test code (2) Refactor decryptAccessToken method to accept access token key and error on failure to pass required decryption key to method. * PM-7392 - Per PR feedback and discussion, do not log the user out if hte refresh token cannot be found. This will allow users to continue to use the app until their access token expires and we will error on trying to refresh it. The app will then still work on a fresh login for 55 min. * PM-7392 - API service - update doAuthRefresh error to clarify which token cannot be refreshed. * PM-7392 - Fix SetRefreshToken case where a null input would incorrectly trigger a fallback to disk. * PM-7392 - If the access token cannot be refreshed due to a missing refresh token or API keys, then surface an error to the user and log it so it isn't a silent failure + we get a log. * PM-7392 - Fix CLI build errors * PM-7392 - Per PR feedback, add missing tests (thank you Jake for writing these!) Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-7392 - Per PR feedback, update incorrect comment from 3 releases to 3 months. * PM-7392 - Per PR feedback, remove links. * PM-7392 - Per PR feedback, move tests to existing describe. * PM-7392 - Per PR feedback, adjust all test names to match naming convention. * PM-7392 - ApiService - refreshIdentityToken - log error before swallowing it so we have a record of it. * PM-7392 - Fix copy for errorRefreshingAccessToken * PM-7392 - Per PR feedback, move error handling toast responsibility to client specific app component logic reached via messaging. * PM-7392 - Swap logout reason from enum to type. * PM-7392 - ApiService - Stop using messaging to trigger toast to let user know about refresh access token errors; replace with client specific callback logic. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * PM-7392 - Per PR feedback, adjust enc string changes and tests. * PM-7392 - Rename file to be type from enum * PM-7392 - ToastService - we need to await the activeToast.onHidden observable so return the activeToast from the showToast. * PM-7392 - Desktop AppComp - cleanup messaging * PM-7392 - Move Logout reason custom type to auth/common * PM-7392 - WIP - Enhancing logout callback to consider the logout reason + move show toast logic into logout callback * PM-7392 - Logout callback should simply pass along the LogoutReason instead of handling it - let each client's message listener handle it. * PM-7392 - More replacements of expired with logoutReason * PM-7392 - More expired to logoutReason replacements * PM-7392 - Build new handlers for displaying the logout reason for desktop & web. * PM-7392 - Revert ToastService changes * PM-7392 - TokenSvc - Replace messageSender with logout callback per PR feedback. * PM-7392 - Desktop App comp - replace toast usage with simple dialog to guarantee users will see the reason for them being logged out. * PM-7392 - Web app comp - fix issue * PM-7392 - Desktop App comp - don't show cancel btn on simple dialogs. * PM-7392 - Desktop App comp - Don't open n simple dialogs. * PM-7392 - Fix browser build * PM-7392 - Remove logout reason from CLI as each logout call handles messaging on its own. * PM-7392 - Previously, if a security stamp was invalid, the session was marked as expired. Restore that functionality. * PM-7392 - Update sync service logoutCallback to include optional user id. * PM-7392 - Clean up web app comp * PM-7392 - Web - app comp - only handle actually possible web logout scenarios. * PM-7392 - Browser Popup app comp - restore done logging out message functionality + add new default logout message * PM-7392 - Add optional user id to logout callbacks. * PM-7392 - Main.background.ts - add clarifying comment. * PM-7392 - Per feedback, use danger simple dialog type for error. * PM-7392 - Browser Popup - add comment clarifying expectation of seeing toasts. * PM-7392 - Consolidate invalidSecurityStamp error handling * PM-7392 - Per PR feedback, REFRESH_ACCESS_TOKEN_ERROR_CALLBACK can be completely sync. + Refactor to method in main.background. * PM-7392 - Per PR feedback, use a named callback for refreshAccessTokenErrorCallback in CLI * PM-7392 - Add TODO * PM-7392 - Re-apply bw.ts changes to new service-container. * PM-7392 - TokenSvc - tweak error message. * PM-7392 - Fix test * PM-7392 - Clean up merge conflict where I duplicated dependencies. * PM-7392 - Per discussion with product, change default logout toast to be info * PM-7392 - After merge, add new logout reason to sync service. * PM-7392 - Remove default logout message per discussion with product since it isn't really visible on desktop or browser. * PM-7392 - address PR feedback. --------- Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2024-06-03 18:36:45 +02:00
private logoutCallback: (logoutReason: LogoutReason) => Promise<void>,
private stateService: StateService,
Login Flows (#4411) * [SG-171] Login with a device request: Desktop (#3999) * Move LoginWithDeviceComponent to libs * Create login module * Remove login component from previous location * Move startPasswordlessLogin method to base class * Register route for login with device component * Add new localizations * Add Login with Device page styles * Add desktop login with device component * Spacing fix * Add content box around page * Update wording of helper text * Make resend timeout a class variable * SG-173 - Login device approval desktop (#4232) * SG-173 Implemented UI and login for login approval request * SG-173 - Show login approval after login * SG-173 Fetch login requests if the setting is true * SG-173 Add subheading to new setting * SG-173 Handle modal dismiss denying login request * SG-173 Fix pr comments * SG-173 Implemented desktop alerts * SG-173 Replicated behaviour of openViewRef * SG-173 Fixed previous commit * SG-173 PR fix * SG-173 Fix PR comment * SG-173 Added missing service injection * SG-173 Added logo to notifications * SG-173 Fix PR comments * [SG-910] Override self hosted check for desktop (#4405) * Override base component self hosted check * Add selfhost check to environment service * [SG-170] Login with Device Request - Browser (#4198) * work: ui stuff * fix: use parent * fix: words * [SG-987] [SG-988] [SG-989] Fix passwordless login request (#4573) * SG-987 Fix notification text and button options * SG-988 Fix approval and decline confirmation toasts * SG-989 Fix methods called * SG-988 Undo previous commit * [SG-1034] [Defect] - Vault is empty upon login confirmation (#4646) * fix: sync after login * undo: whoops --------- Co-authored-by: Carlos Gonçalves <cgoncalves@bitwarden.com> Co-authored-by: Brandon Maharaj <bmaharaj@bitwarden.com> Co-authored-by: Todd Martin <106564991+trmartin4@users.noreply.github.com>
2023-02-05 16:57:21 +01:00
private authService: AuthService,
private messagingService: MessagingService,
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
private taskSchedulerService: TaskSchedulerService,
[Account Switching] [Feature] Allow clients to store data for more than one user (#491) * [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commit e8970725be472386358c1e2f06f53663c4979e0e. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
) {
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
this.taskSchedulerService.registerTaskHandler(
ScheduledTaskNames.notificationsReconnectTimeout,
() => this.reconnect(this.isSyncingOnReconnect),
);
this.environmentService.environment$.subscribe(() => {
if (!this.inited) {
return;
}
2021-12-16 13:36:21 +01:00
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.init();
});
}
2021-12-16 13:36:21 +01:00
async init(): Promise<void> {
this.inited = false;
this.url = (await firstValueFrom(this.environmentService.environment$)).getNotificationsUrl();
2021-12-16 13:36:21 +01:00
// Set notifications server URL to `https://-` to effectively disable communication
// with the notifications server from the client app
if (this.url === "https://-") {
return;
}
if (this.signalrConnection != null) {
2018-08-22 19:48:51 +02:00
this.signalrConnection.off("ReceiveMessage");
2019-07-12 05:05:38 +02:00
this.signalrConnection.off("Heartbeat");
await this.signalrConnection.stop();
this.connected = false;
2018-08-23 14:56:23 +02:00
this.signalrConnection = null;
2018-08-20 19:45:32 +02:00
}
2018-08-23 14:56:23 +02:00
this.signalrConnection = new signalR.HubConnectionBuilder()
.withUrl(this.url + "/hub", {
accessTokenFactory: () => this.apiService.getActiveBearerToken(),
2020-03-21 05:19:40 +01:00
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
2021-12-16 13:36:21 +01:00
})
2018-08-23 14:56:23 +02:00
.withHubProtocol(new signalRMsgPack.MessagePackHubProtocol() as signalR.IHubProtocol)
// .configureLogging(signalR.LogLevel.Trace)
.build();
2021-12-16 13:36:21 +01:00
2018-08-23 14:56:23 +02:00
this.signalrConnection.on("ReceiveMessage", (data: any) =>
this.processNotification(new NotificationResponse(data)),
2021-12-16 13:36:21 +01:00
);
2022-02-22 15:39:11 +01:00
// eslint-disable-next-line
this.signalrConnection.on("Heartbeat", (data: any) => {
2019-07-12 05:05:38 +02:00
/*console.log('Heartbeat!');*/
2021-12-16 13:36:21 +01:00
});
2018-08-20 19:45:32 +02:00
this.signalrConnection.onclose(() => {
this.connected = false;
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
2018-08-23 14:56:23 +02:00
this.reconnect(true);
2021-12-16 13:36:21 +01:00
});
this.inited = true;
if (await this.isAuthedAndUnlocked()) {
2018-08-23 14:56:23 +02:00
await this.reconnect(false);
2018-08-20 19:45:32 +02:00
}
2021-12-16 13:36:21 +01:00
}
2018-08-20 19:45:32 +02:00
async updateConnection(sync = false): Promise<void> {
2018-08-24 21:21:28 +02:00
if (!this.inited) {
2021-12-16 13:36:21 +01:00
return;
}
try {
2018-08-24 21:21:28 +02:00
if (await this.isAuthedAndUnlocked()) {
2018-08-23 14:56:23 +02:00
await this.reconnect(sync);
2018-08-23 03:09:58 +02:00
} else {
2018-08-20 19:45:32 +02:00
await this.signalrConnection.stop();
2021-12-16 13:36:21 +01:00
}
2018-08-20 19:45:32 +02:00
} catch (e) {
this.logService.error(e.toString());
2018-08-23 03:09:58 +02:00
}
2021-12-16 13:36:21 +01:00
}
2018-08-23 03:09:58 +02:00
async reconnectFromActivity(): Promise<void> {
2018-08-23 03:09:58 +02:00
this.inactive = false;
2018-08-24 21:21:28 +02:00
if (this.inited && !this.connected) {
2018-08-23 03:09:58 +02:00
await this.reconnect(true);
}
2021-12-16 13:36:21 +01:00
}
2018-08-23 03:09:58 +02:00
2018-08-20 19:45:32 +02:00
async disconnectFromInactivity(): Promise<void> {
this.inactive = true;
if (this.inited && this.connected) {
2018-08-20 22:01:26 +02:00
await this.signalrConnection.stop();
2021-12-16 13:36:21 +01:00
}
2018-08-20 19:45:32 +02:00
}
[Account Switching] [Feature] Allow clients to store data for more than one user (#491) * [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commit e8970725be472386358c1e2f06f53663c4979e0e. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
private async processNotification(notification: NotificationResponse) {
const appId = await this.appIdService.getAppId();
if (notification == null || notification.contextId === appId) {
return;
}
const isAuthenticated = await this.stateService.getIsAuthenticated();
const payloadUserId = notification.payload.userId || notification.payload.UserId;
const myUserId = await this.stateService.getUserId();
if (isAuthenticated && payloadUserId != null && payloadUserId !== myUserId) {
return;
2018-08-20 19:45:32 +02:00
}
2018-08-23 14:56:23 +02:00
switch (notification.type) {
2018-08-20 19:45:32 +02:00
case NotificationType.SyncCipherCreate:
case NotificationType.SyncCipherUpdate:
await this.syncService.syncUpsertCipher(
notification.payload as SyncCipherNotification,
notification.type === NotificationType.SyncCipherUpdate,
2021-12-16 13:36:21 +01:00
);
2018-08-23 14:56:23 +02:00
break;
2018-08-20 22:01:26 +02:00
case NotificationType.SyncCipherDelete:
2018-08-20 19:45:32 +02:00
case NotificationType.SyncLoginDelete:
2018-08-23 14:56:23 +02:00
await this.syncService.syncDeleteCipher(notification.payload as SyncCipherNotification);
2021-12-16 13:36:21 +01:00
break;
2018-08-23 14:56:23 +02:00
case NotificationType.SyncFolderCreate:
2018-08-20 19:45:32 +02:00
case NotificationType.SyncFolderUpdate:
await this.syncService.syncUpsertFolder(
notification.payload as SyncFolderNotification,
notification.type === NotificationType.SyncFolderUpdate,
2021-12-16 13:36:21 +01:00
);
break;
case NotificationType.SyncFolderDelete:
await this.syncService.syncDeleteFolder(notification.payload as SyncFolderNotification);
break;
case NotificationType.SyncVault:
case NotificationType.SyncCiphers:
2018-08-23 03:09:58 +02:00
case NotificationType.SyncSettings:
if (isAuthenticated) {
await this.syncService.fullSync(false);
2021-12-16 13:36:21 +01:00
}
break;
case NotificationType.SyncOrganizations:
if (isAuthenticated) {
// An organization update may not have bumped the user's account revision date, so force a sync
await this.syncService.fullSync(true);
}
break;
case NotificationType.SyncOrgKeys:
2018-08-23 03:09:58 +02:00
if (isAuthenticated) {
await this.syncService.fullSync(true);
// Stop so a reconnect can be made
await this.signalrConnection.stop();
}
2021-12-16 13:36:21 +01:00
break;
case NotificationType.LogOut:
if (isAuthenticated) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Auth - PM-7392 & PM-7436 - Token Service - Desktop - Add disk fallback for secure storage failures (#8913) * PM-7392 - EncryptSvc - add new method for detecting if a simple string is an enc string. * PM-7392 - TokenSvc - add checks when setting and retrieving the access token to improve handling around the access token encryption. * PM-7392 - (1) Clean up token svc (2) export access token key type for use in tests. * PM-7392 - Get token svc tests passing; WIP more tests to come for new scenarios. * PM-7392 - Access token secure storage to disk fallback WIP but mostly functional besides weird logout behavior. * PM-7392 - Clean up unnecessary comment * PM-7392 - TokenSvc - refresh token disk storage fallback * PM-7392 - Fix token service tests in prep for adding tests for new scenarios. * PM-7392 - TokenSvc tests - Test new setRefreshToken scenarios * PM-7392 - TokenSvc - getRefreshToken should return null or a value - not undefined. * PM-7392 - Fix test name. * PM-7392 - TokenSvc tests - clean up test names that reference removed refresh token migrated flag. * PM-7392 - getRefreshToken tests done. * PM-7392 - Fix error quote * PM-7392 - TokenSvc tests - setAccessToken new scenarios tested. * PM-7392 - TokenSvc - getAccessToken - if secure storage errors add error to log. * PM-7392 - TokenSvc tests - getAccessToken - all new scenarios tested * PM-7392 - EncryptSvc - test new stringIsEncString method * PM-7392 - Main.ts - fix circ dep issue. * PM-7392 - Main.ts - remove comment. * PM-7392 - Don't re-invent the wheel and simply use existing isSerializedEncString static method. * PM-7392 - Enc String - (1) Add handling for Nan in parseEncryptedString (2) Added null handling to isSerializedEncString. (3) Plan to remove encrypt service implementation Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Remove encrypt service method Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - Actually fix circ dep issues with Justin. Ty! Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-7392 - TokenSvc - update to use EncString instead of EncryptSvc + fix tests. * PM-7392 - TokenSvc - (1) Remove test code (2) Refactor decryptAccessToken method to accept access token key and error on failure to pass required decryption key to method. * PM-7392 - Per PR feedback and discussion, do not log the user out if hte refresh token cannot be found. This will allow users to continue to use the app until their access token expires and we will error on trying to refresh it. The app will then still work on a fresh login for 55 min. * PM-7392 - API service - update doAuthRefresh error to clarify which token cannot be refreshed. * PM-7392 - Fix SetRefreshToken case where a null input would incorrectly trigger a fallback to disk. * PM-7392 - If the access token cannot be refreshed due to a missing refresh token or API keys, then surface an error to the user and log it so it isn't a silent failure + we get a log. * PM-7392 - Fix CLI build errors * PM-7392 - Per PR feedback, add missing tests (thank you Jake for writing these!) Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-7392 - Per PR feedback, update incorrect comment from 3 releases to 3 months. * PM-7392 - Per PR feedback, remove links. * PM-7392 - Per PR feedback, move tests to existing describe. * PM-7392 - Per PR feedback, adjust all test names to match naming convention. * PM-7392 - ApiService - refreshIdentityToken - log error before swallowing it so we have a record of it. * PM-7392 - Fix copy for errorRefreshingAccessToken * PM-7392 - Per PR feedback, move error handling toast responsibility to client specific app component logic reached via messaging. * PM-7392 - Swap logout reason from enum to type. * PM-7392 - ApiService - Stop using messaging to trigger toast to let user know about refresh access token errors; replace with client specific callback logic. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * PM-7392 - Per PR feedback, adjust enc string changes and tests. * PM-7392 - Rename file to be type from enum * PM-7392 - ToastService - we need to await the activeToast.onHidden observable so return the activeToast from the showToast. * PM-7392 - Desktop AppComp - cleanup messaging * PM-7392 - Move Logout reason custom type to auth/common * PM-7392 - WIP - Enhancing logout callback to consider the logout reason + move show toast logic into logout callback * PM-7392 - Logout callback should simply pass along the LogoutReason instead of handling it - let each client's message listener handle it. * PM-7392 - More replacements of expired with logoutReason * PM-7392 - More expired to logoutReason replacements * PM-7392 - Build new handlers for displaying the logout reason for desktop & web. * PM-7392 - Revert ToastService changes * PM-7392 - TokenSvc - Replace messageSender with logout callback per PR feedback. * PM-7392 - Desktop App comp - replace toast usage with simple dialog to guarantee users will see the reason for them being logged out. * PM-7392 - Web app comp - fix issue * PM-7392 - Desktop App comp - don't show cancel btn on simple dialogs. * PM-7392 - Desktop App comp - Don't open n simple dialogs. * PM-7392 - Fix browser build * PM-7392 - Remove logout reason from CLI as each logout call handles messaging on its own. * PM-7392 - Previously, if a security stamp was invalid, the session was marked as expired. Restore that functionality. * PM-7392 - Update sync service logoutCallback to include optional user id. * PM-7392 - Clean up web app comp * PM-7392 - Web - app comp - only handle actually possible web logout scenarios. * PM-7392 - Browser Popup app comp - restore done logging out message functionality + add new default logout message * PM-7392 - Add optional user id to logout callbacks. * PM-7392 - Main.background.ts - add clarifying comment. * PM-7392 - Per feedback, use danger simple dialog type for error. * PM-7392 - Browser Popup - add comment clarifying expectation of seeing toasts. * PM-7392 - Consolidate invalidSecurityStamp error handling * PM-7392 - Per PR feedback, REFRESH_ACCESS_TOKEN_ERROR_CALLBACK can be completely sync. + Refactor to method in main.background. * PM-7392 - Per PR feedback, use a named callback for refreshAccessTokenErrorCallback in CLI * PM-7392 - Add TODO * PM-7392 - Re-apply bw.ts changes to new service-container. * PM-7392 - TokenSvc - tweak error message. * PM-7392 - Fix test * PM-7392 - Clean up merge conflict where I duplicated dependencies. * PM-7392 - Per discussion with product, change default logout toast to be info * PM-7392 - After merge, add new logout reason to sync service. * PM-7392 - Remove default logout message per discussion with product since it isn't really visible on desktop or browser. * PM-7392 - address PR feedback. --------- Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com> Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2024-06-03 18:36:45 +02:00
this.logoutCallback("logoutNotification");
2021-12-16 13:36:21 +01:00
}
break;
case NotificationType.SyncSendCreate:
case NotificationType.SyncSendUpdate:
await this.syncService.syncUpsertSend(
notification.payload as SyncSendNotification,
notification.type === NotificationType.SyncSendUpdate,
2021-12-16 13:36:21 +01:00
);
break;
case NotificationType.SyncSendDelete:
await this.syncService.syncDeleteSend(notification.payload as SyncSendNotification);
2022-02-22 15:39:11 +01:00
break;
Login Flows (#4411) * [SG-171] Login with a device request: Desktop (#3999) * Move LoginWithDeviceComponent to libs * Create login module * Remove login component from previous location * Move startPasswordlessLogin method to base class * Register route for login with device component * Add new localizations * Add Login with Device page styles * Add desktop login with device component * Spacing fix * Add content box around page * Update wording of helper text * Make resend timeout a class variable * SG-173 - Login device approval desktop (#4232) * SG-173 Implemented UI and login for login approval request * SG-173 - Show login approval after login * SG-173 Fetch login requests if the setting is true * SG-173 Add subheading to new setting * SG-173 Handle modal dismiss denying login request * SG-173 Fix pr comments * SG-173 Implemented desktop alerts * SG-173 Replicated behaviour of openViewRef * SG-173 Fixed previous commit * SG-173 PR fix * SG-173 Fix PR comment * SG-173 Added missing service injection * SG-173 Added logo to notifications * SG-173 Fix PR comments * [SG-910] Override self hosted check for desktop (#4405) * Override base component self hosted check * Add selfhost check to environment service * [SG-170] Login with Device Request - Browser (#4198) * work: ui stuff * fix: use parent * fix: words * [SG-987] [SG-988] [SG-989] Fix passwordless login request (#4573) * SG-987 Fix notification text and button options * SG-988 Fix approval and decline confirmation toasts * SG-989 Fix methods called * SG-988 Undo previous commit * [SG-1034] [Defect] - Vault is empty upon login confirmation (#4646) * fix: sync after login * undo: whoops --------- Co-authored-by: Carlos Gonçalves <cgoncalves@bitwarden.com> Co-authored-by: Brandon Maharaj <bmaharaj@bitwarden.com> Co-authored-by: Todd Martin <106564991+trmartin4@users.noreply.github.com>
2023-02-05 16:57:21 +01:00
case NotificationType.AuthRequest:
{
this.messagingService.send("openLoginApproval", {
notificationId: notification.payload.id,
});
Login Flows (#4411) * [SG-171] Login with a device request: Desktop (#3999) * Move LoginWithDeviceComponent to libs * Create login module * Remove login component from previous location * Move startPasswordlessLogin method to base class * Register route for login with device component * Add new localizations * Add Login with Device page styles * Add desktop login with device component * Spacing fix * Add content box around page * Update wording of helper text * Make resend timeout a class variable * SG-173 - Login device approval desktop (#4232) * SG-173 Implemented UI and login for login approval request * SG-173 - Show login approval after login * SG-173 Fetch login requests if the setting is true * SG-173 Add subheading to new setting * SG-173 Handle modal dismiss denying login request * SG-173 Fix pr comments * SG-173 Implemented desktop alerts * SG-173 Replicated behaviour of openViewRef * SG-173 Fixed previous commit * SG-173 PR fix * SG-173 Fix PR comment * SG-173 Added missing service injection * SG-173 Added logo to notifications * SG-173 Fix PR comments * [SG-910] Override self hosted check for desktop (#4405) * Override base component self hosted check * Add selfhost check to environment service * [SG-170] Login with Device Request - Browser (#4198) * work: ui stuff * fix: use parent * fix: words * [SG-987] [SG-988] [SG-989] Fix passwordless login request (#4573) * SG-987 Fix notification text and button options * SG-988 Fix approval and decline confirmation toasts * SG-989 Fix methods called * SG-988 Undo previous commit * [SG-1034] [Defect] - Vault is empty upon login confirmation (#4646) * fix: sync after login * undo: whoops --------- Co-authored-by: Carlos Gonçalves <cgoncalves@bitwarden.com> Co-authored-by: Brandon Maharaj <bmaharaj@bitwarden.com> Co-authored-by: Todd Martin <106564991+trmartin4@users.noreply.github.com>
2023-02-05 16:57:21 +01:00
}
break;
default:
break;
}
2021-12-16 13:36:21 +01:00
}
private async reconnect(sync: boolean) {
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
this.reconnectTimerSubscription?.unsubscribe();
2018-08-23 14:56:23 +02:00
if (this.connected || !this.inited || this.inactive) {
2021-12-16 13:36:21 +01:00
return;
}
2018-08-23 14:56:23 +02:00
const authedAndUnlocked = await this.isAuthedAndUnlocked();
if (!authedAndUnlocked) {
return;
}
try {
await this.signalrConnection.start();
this.connected = true;
if (sync) {
await this.syncService.fullSync(false);
}
2018-08-20 19:45:32 +02:00
} catch (e) {
this.logService.error(e);
}
[Account Switching] [Feature] Allow clients to store data for more than one user (#491) * [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commit e8970725be472386358c1e2f06f53663c4979e0e. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
if (!this.connected) {
[PM-6426] Create TaskSchedulerService and update long lived timeouts in the extension to leverage the new service (#8566) * [PM-6426] Create TaskSchedulerService and update usage of long lived timeouts * [PM-6426] Implementing nextSync timeout using TaskScheduler * [PM-6426] Implementing systemClearClipboard using TaskScheduler * [PM-6426] Fixing race condition with setting/unsetting active alarms * [PM-6426] Implementing clear clipboard call on generatePasswordToClipboard with the TaskSchedulerService * [PM-6426] Implementing abortTimeout for Fido2ClientService using TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing reconnect timer timeout for NotificationService using the TaskSchedulerService * [PM-6426] Implementing sessionTimeout for LoginStrategyService using TaskSchedulerService * [PM-6426] Implementing eventUploadInterval using TaskScheduler * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Updating jest tests for GeneratePasswordToClipboardCommand * [PM-6426] Setting up the full sync process as an interval rather than a timeout * [PM-6426] Renaming the scheduleNextSync alarm name * [PM-6426] Fixing dependency references in services.module.ts * [PM-6426] Adding jest tests for added BrowserApi methods * [PM-6426] Refactoring small detail for how we identify the clear clipboard timeout in SystemService * [PM-6426] Ensuring that we await clearing an established scheduled task for the notification service * [PM-6426] Changing the name of the state definition for the TaskScheduler * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Implementing jest tests for the BrowserTaskSchedulerService * [PM-6426] Adding jest tests for the base TaskSchedulerService class * [PM-6426] Finalizing jest tests for BrowserTaskScheduler class * [PM-6426] Finalizing documentation on BrowserTaskSchedulerService * [PM-6426] Fixing jest test for LoginStrategyService * [PM-6426] Implementing compatibility for the browser.alarms api * [PM-6426] Fixing how we check for the browser alarms api * [PM-6426] Adding jest tests to the BrowserApi implementation * [PM-6426] Aligning the implementation with our code guidelines for Angular components * [PM-6426] Fixing jest tests and lint errors * [PM-6426] Moving alarms api calls out of BrowserApi and structuring them within the BrowserTaskSchedulerService * [PM-6426] Reworking implementation to register handlers separately from the call to those handlers * [PM-6426] Adjusting how we register the fullSync scheduled task * [PM-6426] Implementing approach for incorporating the user UUID when setting task handlers * [PM-6426] Attempting to re-work implementation to facilitate userId-spcific alarms * [PM-6426] Refactoring smaller details of the implementation * [PM-6426] Working through the details of the implementation and setting up final refinments * [PM-6426] Fixing some issues surrounding duplicate alarms triggering * [PM-6426] Adjusting name for generate password to clipboard command task name * [PM-6426] Fixing generate password to clipboard command jest tests * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Working through jest tests and implementing a method to guard against setting a task without having a registered callback * [PM-6426] Implementing methodology for having a fallback to setTimeout if the browser context is lost in some manner * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Working through jest tests * [PM-6426] Finalizing stepped setInterval implementation * [PM-6426] Implementing Jest tests for DefaultTaskSchedulerService * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Adjusting jest tests * [PM-6426] Fixing issues identified in code review * [PM-6426] Fixing issues identified in code review * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Removing user-based alarms and fixing an issue found with setting steppedd alarm interavals * [PM-6426] Fixing issue with typing information on a test * [PM-6426] Using the getUpperBoundDelayInMinutes method to handle setting stepped alarms and setTimeout fallbacks * [PM-6426] Removing the potential for the TaskScheduler to be optional * [PM-6426] Reworking implementation to leverage subscription based deregistration of alarms * [PM-6426] Fixing jest tests * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Implementing foreground and background task scheduler services to avoid duplication of task scheudlers and to have the background setup as a fallback to the poopup tasks * [PM-6426] Merging main into branch * [PM-6426] Fixing issues with the CLI Service Container implementation * [PM-6426] Reworking swallowed promises to contain a catch statement allow us to debug potential issues with registrations of alarms * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adding jest tests to the ForegroundTaskSchedulerService and the BackgroundTaskSchedulerService * [PM-6426] Adjusting implementation based on code review feedback * [PM-6426] Reworking file structure * [PM-6426] Reworking file structure * [PM-6426] Adding comments to provide clarity on how the login strategy cache experiation state is used * [PM-6426] Catching and logging erorrs that appear from methods that return a promise within VaultTimeoutService
2024-07-15 17:32:30 +02:00
this.isSyncingOnReconnect = sync;
this.reconnectTimerSubscription = this.taskSchedulerService.setTimeout(
ScheduledTaskNames.notificationsReconnectTimeout,
this.random(120000, 300000),
);
}
2021-12-16 13:36:21 +01:00
}
private async isAuthedAndUnlocked() {
const authStatus = await this.authService.getAuthStatus();
return authStatus >= AuthenticationStatus.Unlocked;
2021-12-16 13:36:21 +01:00
}
private random(min: number, max: number) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
2021-12-16 13:36:21 +01:00
}
2018-08-20 19:45:32 +02:00
}