bitwarden-browser/apps/browser/src/auth/popup/account-switching/services/account-switcher.service.ts

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

162 lines
5.5 KiB
TypeScript
Raw Normal View History

[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
import { Injectable } from "@angular/core";
import {
Observable,
combineLatest,
filter,
firstValueFrom,
map,
switchMap,
throwError,
timeout,
} from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AvatarService } from "@bitwarden/common/auth/abstractions/avatar.service";
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { UserId } from "@bitwarden/common/types/guid";
import { fromChromeEvent } from "../../../../platform/browser/from-chrome-event";
export type AvailableAccount = {
name: string;
email?: string;
id: string;
isActive: boolean;
server?: string;
status?: AuthenticationStatus;
avatarColor?: string;
};
@Injectable({
providedIn: "root",
})
export class AccountSwitcherService {
static incompleteAccountSwitchError = "Account switch did not complete.";
ACCOUNT_LIMIT = 5;
SPECIAL_ADD_ACCOUNT_ID = "addAccount";
availableAccounts$: Observable<AvailableAccount[]>;
switchAccountFinished$: Observable<string>;
constructor(
private accountService: AccountService,
private avatarService: AvatarService,
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
private messagingService: MessagingService,
private environmentService: EnvironmentService,
private logService: LogService,
) {
this.availableAccounts$ = combineLatest([
this.accountService.accounts$,
this.accountService.activeAccount$,
]).pipe(
switchMap(async ([accounts, activeAccount]) => {
const accountEntries = Object.entries(accounts).filter(
([_, account]) => account.status !== AuthenticationStatus.LoggedOut,
);
// Accounts shouldn't ever be more than ACCOUNT_LIMIT but just in case do a greater than
const hasMaxAccounts = accountEntries.length >= this.ACCOUNT_LIMIT;
const options: AvailableAccount[] = await Promise.all(
accountEntries.map(async ([id, account]) => {
return {
name: account.name ?? account.email,
email: account.email,
id: id,
server: (await this.environmentService.getEnvironment(id))?.getHostname(),
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
status: account.status,
isActive: id === activeAccount?.id,
avatarColor: await firstValueFrom(
this.avatarService.getUserAvatarColor$(id as UserId),
),
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
};
}),
);
if (!hasMaxAccounts) {
options.push({
name: "Add account",
id: this.SPECIAL_ADD_ACCOUNT_ID,
isActive: false,
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
});
}
return options.sort((a, b) => {
/**
* Make sure the compare function is "well-formed" to account for browser inconsistencies.
*
* For specifics, see the sections "Description" and "Sorting with a non-well-formed comparator"
* on this page:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
*/
// Active account (if one exists) is always first
if (a.isActive) {
return -1;
}
// If account "b" is the 'Add account' button, keep original order of "a" and "b"
if (b.id === this.SPECIAL_ADD_ACCOUNT_ID) {
return 0;
}
return 1;
});
[PM-194] Browser Account Switcher UI (#6772) * Handle switch messaging TODO: handle loading state for account switcher * Async updates required for state * Fallback to email for current account avatar * Await un-awaited promises * Remove unnecessary Prune Prune was getting confused in browser and deleting memory in browser on account switch. This method isn't needed since logout already removes memory data, which is the condition for pruning * Fix temp password in browser * Use direct memory access until data is serializable Safari uses a different message object extraction than firefox/chrome and is removing `UInt8Array`s. Until all data passed into StorageService is guaranteed serializable, we need to use direct access in state service * Reload badge and context menu on switch * Gracefully switch account as they log out. * Maintain location on account switch * Remove unused state definitions * Prefer null for state undefined can be misinterpreted to indicate a value has not been set. * Hack: structured clone in memory storage We are currently getting dead objects on account switch due to updating the object in the foreground state service. However, the storage service is owned by the background. This structured clone hack ensures that all objects stored in memory are owned by the appropriate context * Null check nullable values active account can be null, so we should include null safety in the equality * Correct background->foreground switch command * Already providing background memory storage * Handle connection and clipboard on switch account * Prefer strict equal * Ensure structuredClone is available to jsdom This is a deficiency in jsdom -- https://github.com/jsdom/jsdom/issues/3363 -- structured clone is well supported. * Fixup types in faker class * add avatar and simple navigation to header * add options buttons * add app-header to necessary pages * add back button and adjust avatar sizes * add helper text when account limit reached * convert magic number to constant * add clarifying comment * adjust homepage header styles * navigate to previousp page upon avatar click when already on '/account-switcher' * move account UI to own component * add i18n * show correct auth status * add aria-hidden to icons * use listbox role * add screen reader accessibility to account component * more SR a11y updates to account component * add hover and focus states to avatar * refactor hover and focus states for avatar * add screen reader text for avatar * add slide-down animation on account switcher close * remove comment * setup account component story * add all stories * move navigation call to account component * implement account lock * add button hover effect * implement account logout * implement lockAll accounts functionality * replace 'any' with custom type * add account switcher button to /home login page * use <main> tag (enables scrolling) * change temp server filler name * temporarily remove server arg from account story * don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount * add translation and a11y to /home avatar * add correct server url to account component * add 'server' to AccountOption type * Enabled account switching client-side feature flag. * add slide-in transition to /account-switcher page * change capitalization to reflect figma design * make screen reader read active account email, address more capitalization * fix web avatar misalignment * make avatar color based on user settings and in sync with other clients * make property private * change accountOptions to availableAccounts for clarity * refactor to remove 'else' template ref * remove empty scss rule * use tailwind instead of scss * rename isSelected to isActive * add 'isButton' to /home page avatar * move files to services folder * update import * Remove duplicate active account button * Move no account button to current-account component * Always complete logging out Fixes PM-4866 * make screenreader read off email, not name * refactor avatar for button case * Do not next object updates StateService's init was calling `updateState` at multiple layers, once overall and then again for each account updated. Because we were not maintaining a single state object through the process, it was ending up in a consistent, but incomplete state. Fixed by returning the updated state everywhere. This very well may not be all the bugs associated with this * Treat null switch account as no active user * Listen for switchAccountFinish before routing (#6950) * adjust avatar style when wrapped in a button * show alt text for favicon setting * move stories to browser * Send Finish Message on null * Dynamically set active user when locking all This is required because some user lock states are not recoverable after process reload (those with logout timeout). This waits until reload is occurring, then sets the next user appropriately * Move Finished Message to Finally Block Fix tests * Drop problematic key migration Fixes PM-4933. This was an instance of foreground/background collision when writing state. We have several other fallbacks of clearing these deprecated keys. * Prefer location to homebrew router service * Initialize account disk cache from background Uses the `isRecoveredSession` bool to re-initialize foreground caches from a background message. This avoids a lengthy first-read for foregrounds * PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991) * Lock of active account first, when locking multiple. Fixes PM-4996 * Fix linter * Hide lock now for locked users (#7020) * Hide lock now for locked users * Prefer disabling button to removing * Add tooltip to TDE without unlock method * Load all auth states on state init (#7027) This is a temporary fix until the owning services can update state themselves. It uses the presence of an auto key to surmise unlocked state on init. This is safe since it's run only once on extension start. * Ps/pm 5004/add load to account switcher (#7032) * Add load spinner to account switcher * Remove ul list icons * Properly size account switcher in popout * [PM-5005] Prevent Double Navigation (#7035) * Delete Overriden Method * Add Lock Transition * truncate email and server name * remove account.stories.ts (will add in separate PR) * Do not switch user at reload if no user is active * fix prettier issues --------- Co-authored-by: Matt Gibson <mgibson@bitwarden.com> Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: bnagawiecki <107435978+bnagawiecki@users.noreply.github.com>
2023-12-06 18:22:48 +01:00
}),
);
// Create a reusable observable that listens to the the switchAccountFinish message and returns the userId from the message
this.switchAccountFinished$ = fromChromeEvent<[message: { command: string; userId: string }]>(
chrome.runtime.onMessage,
).pipe(
filter(([message]) => message.command === "switchAccountFinish"),
map(([message]) => message.userId),
);
}
get specialAccountAddId() {
return this.SPECIAL_ADD_ACCOUNT_ID;
}
async selectAccount(id: string) {
if (id === this.SPECIAL_ADD_ACCOUNT_ID) {
id = null;
}
// Creates a subscription to the switchAccountFinished observable but further
// filters it to only care about the current userId.
const switchAccountFinishedPromise = firstValueFrom(
this.switchAccountFinished$.pipe(
filter((userId) => userId === id),
timeout({
// Much longer than account switching is expected to take for normal accounts
// but the account switching process includes a possible full sync so we need to account
// for very large accounts and want to still have a timeout
// to avoid a promise that might never resolve/reject
first: 60_000,
with: () =>
throwError(() => new Error(AccountSwitcherService.incompleteAccountSwitchError)),
}),
),
);
// Initiate the actions required to make account switching happen
await this.accountService.switchAccount(id as UserId);
this.messagingService.send("switchAccount", { userId: id }); // This message should cause switchAccountFinish to be sent
// Wait until we recieve the switchAccountFinished message
await switchAccountFinishedPromise.catch((err) => {
if (
err instanceof Error &&
err.message === AccountSwitcherService.incompleteAccountSwitchError
) {
this.logService.warning("message 'switchAccount' never responded.");
return;
}
throw err;
});
}
}