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

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

189 lines
4.5 KiB
TypeScript
Raw Normal View History

import { Observable, Subject } from "rxjs";
import {
EnvironmentService as EnvironmentServiceAbstraction,
Urls,
} from "../abstractions/environment.service";
[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
import { StateService } from "../abstractions/state.service";
2022-02-22 15:39:11 +01:00
import { EnvironmentUrls } from "../models/domain/environmentUrls";
2018-01-10 02:20:54 +01:00
2018-01-23 23:29:15 +01:00
export class EnvironmentService implements EnvironmentServiceAbstraction {
private readonly urlsSubject = new Subject<Urls>();
2022-02-22 15:39:11 +01:00
urls: Observable<Urls> = this.urlsSubject;
2021-12-16 13:36:21 +01:00
private baseUrl: string;
private webVaultUrl: string;
private apiUrl: string;
private identityUrl: string;
private iconsUrl: string;
private notificationsUrl: string;
private eventsUrl: string;
private keyConnectorUrl: string;
2021-12-16 13:36:21 +01:00
Misc Account Switching Fixes & Refactors (#600) * [refactor] Restructure EnvironmentUrls in state * Patch up (add missing fields) and more extensivly use the EnvironmentUrls class instead of passing around an any * Add environmentUrls to the AccountSettings model in addition to GlobalState for use in both scopes * Move EnvironmentUrls initialization to the model level and out of StateSerice * Adjust the StateMigrationService to account for these changes * [refactor] Improve order of operations for LockGuardService We currently jump through a bunch of hoops to verify users can access the Lock page, like checking authentication first. If a user is not authenticated, they are not locked, so we can improve performance for the happy path of this serivice by checking isLocked first and using isAuthenticated to deviate from the normal flow if needed. * [bug] Subscribe to State.accounts in EnvironmentService and set urls accordingly The EnvironmentService has no context for account changes currently and does not update actively used urls based on active account. This commit addresses this issue by subscribing to State.accounts and resetting the service's urls on account change. * [bug] Clear AccessToken from State on clean In order for logout flows to function as expected we need to deauthenticate users when cleaning up state before checking for the next active user Otherwise the service will continue to think the user being logged out is active * [refactor] Stop pushing accounts when modifying disk state There is no reason to push new accounts to subscribers when updating disk state. Subscribers recieve a copy of in memory state, so changes to disk will not be refelected and have to be fetched seperatly from the service. Pushing when saving disk state is just creating an unecassary performance burden. * [refactor] Default to in memory active user if availible, even when accessing disk state Sometimes we need to pull activeUserId from storage to access a bit of data, like on initial boot, but most of the time this isn't necassary. Since we pull this userId a lot, checking disk each time is a performance burden. Defaulting to the in memory user ID if avaible helps alleviate this. * [style] Ran prettier * [style] Change a let to a const
2022-01-07 15:30:54 +01:00
constructor(private stateService: StateService) {
2022-02-22 15:39:11 +01:00
this.stateService.activeAccount.subscribe(async () => {
Misc Account Switching Fixes & Refactors (#600) * [refactor] Restructure EnvironmentUrls in state * Patch up (add missing fields) and more extensivly use the EnvironmentUrls class instead of passing around an any * Add environmentUrls to the AccountSettings model in addition to GlobalState for use in both scopes * Move EnvironmentUrls initialization to the model level and out of StateSerice * Adjust the StateMigrationService to account for these changes * [refactor] Improve order of operations for LockGuardService We currently jump through a bunch of hoops to verify users can access the Lock page, like checking authentication first. If a user is not authenticated, they are not locked, so we can improve performance for the happy path of this serivice by checking isLocked first and using isAuthenticated to deviate from the normal flow if needed. * [bug] Subscribe to State.accounts in EnvironmentService and set urls accordingly The EnvironmentService has no context for account changes currently and does not update actively used urls based on active account. This commit addresses this issue by subscribing to State.accounts and resetting the service's urls on account change. * [bug] Clear AccessToken from State on clean In order for logout flows to function as expected we need to deauthenticate users when cleaning up state before checking for the next active user Otherwise the service will continue to think the user being logged out is active * [refactor] Stop pushing accounts when modifying disk state There is no reason to push new accounts to subscribers when updating disk state. Subscribers recieve a copy of in memory state, so changes to disk will not be refelected and have to be fetched seperatly from the service. Pushing when saving disk state is just creating an unecassary performance burden. * [refactor] Default to in memory active user if availible, even when accessing disk state Sometimes we need to pull activeUserId from storage to access a bit of data, like on initial boot, but most of the time this isn't necassary. Since we pull this userId a lot, checking disk each time is a performance burden. Defaulting to the in memory user ID if avaible helps alleviate this. * [style] Ran prettier * [style] Change a let to a const
2022-01-07 15:30:54 +01:00
await this.setUrlsFromStorage();
});
}
2021-12-16 13:36:21 +01:00
hasBaseUrl() {
return this.baseUrl != null;
2021-12-16 13:36:21 +01:00
}
getNotificationsUrl() {
if (this.notificationsUrl != null) {
return this.notificationsUrl;
}
if (this.baseUrl != null) {
return this.baseUrl + "/notifications";
}
2018-06-25 14:06:19 +02:00
return "https://notifications.bitwarden.com";
}
getWebVaultUrl() {
if (this.webVaultUrl != null) {
2018-06-25 14:06:19 +02:00
return this.webVaultUrl;
}
if (this.baseUrl) {
return this.baseUrl;
}
return "https://vault.bitwarden.com";
2021-12-16 13:36:21 +01:00
}
getSendUrl() {
return this.getWebVaultUrl() === "https://vault.bitwarden.com"
? "https://send.bitwarden.com/#"
: this.getWebVaultUrl() + "/#/send/";
2021-12-16 13:36:21 +01:00
}
getIconsUrl() {
if (this.iconsUrl != null) {
return this.iconsUrl;
}
if (this.baseUrl) {
return this.baseUrl + "/icons";
}
return "https://icons.bitwarden.net";
}
getApiUrl() {
if (this.apiUrl != null) {
return this.apiUrl;
}
if (this.baseUrl) {
return this.baseUrl + "/api";
}
return "https://api.bitwarden.com";
}
getIdentityUrl() {
if (this.identityUrl != null) {
return this.identityUrl;
}
if (this.baseUrl) {
return this.baseUrl + "/identity";
}
return "https://identity.bitwarden.com";
}
getEventsUrl() {
if (this.eventsUrl != null) {
return this.eventsUrl;
2018-01-10 02:20:54 +01:00
}
if (this.baseUrl) {
return this.baseUrl + "/events";
}
return "https://events.bitwarden.com";
2021-12-16 13:36:21 +01:00
}
getKeyConnectorUrl() {
return this.keyConnectorUrl;
2021-12-16 13:36:21 +01:00
}
2018-01-10 02:20:54 +01:00
async setUrlsFromStorage(): Promise<void> {
const urls: any = await this.stateService.getEnvironmentUrls();
2018-01-10 02:20:54 +01:00
const envUrls = new EnvironmentUrls();
2021-12-16 13:36:21 +01:00
this.baseUrl = envUrls.base = urls.base;
2018-01-10 02:20:54 +01:00
this.webVaultUrl = urls.webVault;
this.apiUrl = envUrls.api = urls.api;
this.identityUrl = envUrls.identity = urls.identity;
this.iconsUrl = urls.icons;
2018-08-20 19:45:32 +02:00
this.notificationsUrl = urls.notifications;
2019-06-20 14:56:45 +02:00
this.eventsUrl = envUrls.events = urls.events;
this.keyConnectorUrl = urls.keyConnector;
2021-12-16 13:36:21 +01:00
}
async setUrls(urls: Urls): Promise<Urls> {
2018-01-10 02:20:54 +01:00
urls.base = this.formatUrl(urls.base);
urls.webVault = this.formatUrl(urls.webVault);
urls.api = this.formatUrl(urls.api);
urls.identity = this.formatUrl(urls.identity);
urls.icons = this.formatUrl(urls.icons);
2018-08-20 19:45:32 +02:00
urls.notifications = this.formatUrl(urls.notifications);
2019-06-20 14:56:45 +02:00
urls.events = this.formatUrl(urls.events);
urls.keyConnector = this.formatUrl(urls.keyConnector);
2021-12-16 13:36:21 +01:00
await this.stateService.setEnvironmentUrls({
base: urls.base,
api: urls.api,
identity: urls.identity,
webVault: urls.webVault,
icons: urls.icons,
notifications: urls.notifications,
events: urls.events,
keyConnector: urls.keyConnector,
});
2018-01-10 02:20:54 +01:00
this.baseUrl = urls.base;
this.webVaultUrl = urls.webVault;
this.apiUrl = urls.api;
this.identityUrl = urls.identity;
this.iconsUrl = urls.icons;
2018-08-20 19:45:32 +02:00
this.notificationsUrl = urls.notifications;
2019-06-20 14:56:45 +02:00
this.eventsUrl = urls.events;
this.keyConnectorUrl = urls.keyConnector;
2021-12-16 13:36:21 +01:00
this.urlsSubject.next(urls);
2021-12-16 13:36:21 +01:00
2018-01-10 02:20:54 +01:00
return urls;
2021-12-16 13:36:21 +01:00
}
getUrls() {
2021-12-16 13:36:21 +01:00
return {
base: this.baseUrl,
webVault: this.webVaultUrl,
api: this.apiUrl,
identity: this.identityUrl,
icons: this.iconsUrl,
notifications: this.notificationsUrl,
events: this.eventsUrl,
keyConnector: this.keyConnectorUrl,
2021-12-16 13:36:21 +01:00
};
}
private formatUrl(url: string): string {
2018-01-10 02:20:54 +01:00
if (url == null || url === "") {
return null;
2021-12-16 13:36:21 +01:00
}
2018-01-10 02:20:54 +01:00
url = url.replace(/\/+$/g, "");
2019-06-20 14:56:45 +02:00
if (!url.startsWith("http://") && !url.startsWith("https://")) {
2018-01-10 02:20:54 +01:00
url = "https://" + url;
}
2021-12-16 13:36:21 +01:00
2019-02-15 22:53:01 +01:00
return url.trim();
2021-12-16 13:36:21 +01:00
}
2018-01-10 02:20:54 +01:00
}