bitwarden-estensione-browser/apps/desktop/src/app/services/services.module.ts

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

291 lines
12 KiB
TypeScript
Raw Normal View History

import { APP_INITIALIZER, NgModule } from "@angular/core";
import { Subject, merge } from "rxjs";
import { SafeProvider, safeProvider } from "@bitwarden/angular/platform/utils/safe-provider";
import {
SECURE_STORAGE,
LOCALES_DIRECTORY,
SYSTEM_LANGUAGE,
PS-813 Add memory storage to state service (#2892) * Use abstract methods and generics in StorageService * Prepend `Abstract` to abstract classes * Create session browser storage service * Use memory storage service for state memory * Inject memory storage service * Maintain filename extensions to help ide formatting * Preserve state if it's still in memory * Use jslib's memory storage service * linter * Create prototypes on stored objects * standardize package scripts * Add type safety to `withPrototype` decorators * webpack notify manifest version * Fix desktop * linter * Fix script * Improve prototye application * do not change prototype if it already matches desired * fix error with object values prototype application * Handle null state * Apply prototypes to browser-specific state * Add angular language server to recommended extensions * Improve browser state service tests * Start testing state Service * Fix abstract returns * Move test setup files to not be picked up by default glob matchers * Add key generation service * Add low-dependency encrypt service * Back crypto service with encrypt service. We'll want to work items that don't require state over to encrypt service * Add new storage service and tests * Properly init more stored values * Fix reload issues when state service is recovering state from session storage Co-authored-by: Thomas Avery <Thomas-Avery@users.noreply.github.com> Co-authored-by: Justin Baur <admin@justinbaur.com> * Simplify encrypt service * Do not log mac failures for local-backed session storage * `content` changed to `main` in #2245 * Fix CLI * Remove loggin * PR feedback * Merge remote-tracking branch 'origin/master' into add-memory-storage-to-state-service * Fix desktop * Fix decrypt method signature * Minify if not development * Key is required Co-authored-by: Thomas Avery <Thomas-Avery@users.noreply.github.com> Co-authored-by: Justin Baur <admin@justinbaur.com>
2022-06-27 19:38:12 +02:00
MEMORY_STORAGE,
OBSERVABLE_MEMORY_STORAGE,
OBSERVABLE_DISK_STORAGE,
WINDOW,
Auth/PM-5263 - TokenService State Provider Migration (#7975) * PM-5263 - Token Service state migration - (1) Got key and state definitions setup (2) Ported over core state service getTimeoutBasedStorageOptions method logic into local determineStorageLocation method (3) Updated majority of methods to use state provider state * PM-5263 - StateSvc - add TODO to remove timeoutBasedStorageOptions + other state methods after migration code complete. * PM-5263 - TokenSvc - ClearToken method - (1) Update signature to remove user id as it wasn't used and it simplifies the new state provider implementation (2) Convert away from state svc to state provider state. * PM-5263 - TokenService - update deps - WIP on circular dep issues. * PM-5263 - To resolve circular dep issues between VaultTimeoutSettingsSvc and TokenService: (1) For writes, require callers to pass in vault timeout data (2) For reads, we can just check both locations. This approach has 1 less state call than the previous implementation and is safe as long as the clear logic properly works and is executed anytime a user changes their vault timeout action (lock or log out) & vault timeout (numeric value) * PM-5263 - VaultTimeoutSettingsSvc - Set token calls now updated to include vault timeout info. * PM-5263 - Update API Service - add state service and look up vault timeout details and pass to token service when setting token info. * PM-5263 - TokenService - update service dependencies. * PM-5263 - TokenService - Add new getAccessTokenByUserId method for state service use case. * PM-5263 - StateSvc - remove migrated methods and try to replace all usages of getAccessToken. WIP * PM-5263 - TokenSvc Migration - start on migrator * PM-5263 - (1) TokenSvc - Build new clearAccessTokenByUserId which is required by state service (2) TokenSvc - Update getToken to take an optional userId to handle another state service case (3) Add some documentation to TokenSvc abstraction. * PM-5263 - StateService - finish updating all calls within the state service which accessed token service state directly with calls to the new token service methods instead. * PM-5263 - TokenSvc Abstraction - Add more docs * PM-5263 - TokenSvc abstraction - more doc tweaks * PM-5263 - Web state service - add new token service dependency. * PM-5263 - User API Key Login Strategy - Update to pull vault timeout action and vault timeout from state service in order to pass to new token service endpoints for setting API key client id and secret. * PM-5263 - (1) Remove TokenSvc owned state from account (2) StateSvc - remove account scaffold logic for clearing removed account data. The same functionality will exist in the state provider framework via lifecycle hooks cleaning up this data and users getting initialized with null data by default. * PM-5263 - Add token service dependency to state service (WIP - desktop deps not working) * PM-5263 - Update services module on desktop and browser to add token svc dependency * PM-5263 - API service factory - add state service factory dependency that I missed initially to get browser building. * PM-5263 - TokenSvc - getToken/setToken/decodeToken --> getAccessToken/setAccessToken/decodeAccessToken * PM-5263 - TokenSvc State Provider Migrator - WIP - update expected acct type to match actual account * PM-5263 - TokenService - clearToken renamed to clearTokens * PM-5263 - CLI - NodeApiService - add state service dep to get CLI building. * PM-5263 - StateDefinitions - use unique state definition names * PM-5263 - StateSvc - remove getTimeoutBasedStorageOptions as no longer used. * PM-5263 - TokenSvc - Add TODO for figuring out how to store tokens in secure storage. * PM-5263 - StateSvc - remove get/set 2FA token - references migrated later. * PM-5263 - TODO: figure out if using same key definition names is an issue * PM-5263 - TokenServiceStateProviderMigrator written * PM-5263 - TokenServiceStateProviderMigrator - (1) Don't update legacy account if we only added a new state in state provider for 2FA token (2) Use for loop for easier debugging * PM-5263 - TokenServiceStateProviderMigrator test - WIP - migration testing mostly complete and passing. Rollback logic TODO. * PM-5263 - TokenServiceStateProviderMigrator - Add rollback logic to restore 2FA token from users to global. * PM-5263 - TokenServiceStateProviderMigrator - Refactor rollback to only set account once as not necessary to set it every time. * PM-5263 - TokenServiceStateProviderMigrator tests - test all rollback scenarios * PM-5263 - Remove TODO as don't need unique key def names as long as state def keys are unique. * PM-5263 - TokenSvc - update clearAccessTokenByUserId to use proper state provider helper method to set state. * PM-5263 - Revert accidentally committing settings.json changes. * PM-5263 - TokenSvc - update all 2FA token methods to require email so we can user specifically scope 2FA tokens while still storing them in global storage. * PM-5263 - Update all token service 2FA set / get / clear methods to pass in email. * PM-5263 - JslibServices module - add missed login service to login strategy svc deps. * PM-5263 - VaultTimeoutSettingsService - setVaultTimeoutOptions - rename token to accesToken for clarity. * PM-5263 - (1) TokenSvc - remove getAccessTokenByUserId and force consumers to use getAccessToken w/ optional user id to keep interface small (2) TokenSvc - attempt to implement secure storage on platforms that support it for access & refresh token storage (3) StateSvc - replace usage of getAccessTokenByUserId with getAccessToken * PM-5263 - TokenSvc - add platform utils and secure storage svc deps * PM-5263 - TODO: figure out what to do with broken migration * PM-5263 - TODO: update tests in light of latest 2FA token changes. * PM-5263 - TokenSvc - clean up TODO * PM-5263 - We should have tests for the token service. * PM-5263 - TokenSvc - setAccessToken - If platform supports secure storage and we are saving an access token, remove the access token from memory and disk to fully migrate to secure storage. * PM-5263 - TokenSvc - getAccessToken - Update logic to look at memory and disk first always and secure storage last to support the secure storage migration * PM-5263 - TokenSvc - setAccesToken - if user id null on a secure storage supporting platform, throw error. * PM-5263 - TokenService - (1) Refresh token now stored in secure storage (2) Refresh token set now private as we require a user id to store it in secure storage and we can use the setTokens method to enforce always setting the access token and refresh token together in order to extract a user id from the refresh token. (3) setTokens clientIdClientSecret param now optional * PM-5263 - TokenServiceStateProviderMigrator - update migration to take global but user scoped 2FA token storage changes into account. * PM-5263 - Remove old migration as it references state we are removing. Bump min version. Co-authored-by: Matt Gibson <git@mgibson.dev> * PM-5263 - TokenService - 2FA token methods now backed by global state record which maps email to individual tokens. * PM-5263 - WIP on Token Svc migrator and test updates based on new 2FA token storage changes. * PM-5263 - TokenSvc - (1) Add jira tickets to clean up state migration (2) Add state to track secure storage migration to improve # of reads to get data * PM-5263 - StateDef - consolidate name of token domain state defs per feedback from Justin + update migration tests * PM-5263 - TokenSvc - fix error message and add TODO * PM-5263 - Update token service migration + tests to pass after all 2FA token changes. * PM-5263 - Fix all login strategy tests which were failing due to token state provider changes + the addition of the loginService as a dependency in the base login strategy. * PM-5263 - Register TokenService state provider migration with migrator * PM-5263 - TokenSvc state migration - set tokens after initializing account * PM-5263 - TokenService changes - WIP - convert from ActiveUserStateProvider to just SingleUserStateProvider to avoid future circ dependency issues. Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> * PM-5263 - TokenSvc - create getSecureStorageOptions for centralizing all logic for getting data out of SecureStorage. * PM-5263 - TokenSvc - (1) Refactor determineStorageLocation to also determine secure storage - created a TokenStorageLocation string enum to remove magic strings (2) Refactor setAccessToken to use switch (3) Refactor clearAccessTokenByUserId to clear all locations and not early return on secure storage b/c we only use secure storage if disk is the location but I don't want to require vault timeout data for this method. * PM-5263 - TokenSvc - getDataFromSecureStorage - Refactor to be more generic for easier re-use * PM-5263 - TokenSvc - Convert refresh token methods to use single user state and require user ids * PM-5263 - VaultTimeoutSettingsSvc - get user id and pass to access and refresh token methods. * PM-5263 - TokenSvc - refactor save secure storage logic into private helper. * PM-5263 - Base Login Strategy - per discussion with Justin, move save of tokens to before account initialization as we can always derive the user id from the access token. This will ensure that the account is initialized with the proper authN status. * PM-5263 - TokenSvc - latest refactor - update all methods to accept optional userId now as we can read active user id from global state provider without using activeUserStateProvider (thus, avoiding a circular dep and having to have every method accept in a mandatory user id). * PM-5263 - VaultTimeoutSettingsService - remove user id from token calls * PM-5263 - TokenSvc - update all places we instantiate token service to properly pass in new deps. * PM-5263 - TokenSvc migration is now 27th instead of 23rd. * PM-5263 - Browser - MainContextMenuHandler - Update service options to include PlatformUtilsServiceInitOptions as the TokenService requires that and the TokenService is now injected on the StateService * PM-5263 - TokenSvc migration test - update rollback tests to start with correct current version * PM-5263 - Create token service test file - WIP * PM-5263 - TokenSvc - tests WIP - instantiates working. * PM-5263 - TokenSvc - set2FAToken - use null coalesce to ensure record is instantiated for new users before setting data on it. * PM-5263 - TokenService tests - WIP - 2FA token tests. * PM-5263 - Worked with Justin to resolve desktop circular dependency issue by adding SUPPORTS_SECURE_STORAGE injection token instead of injecting PlatformUtilsService directly into TokenService. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - WIP - (1) Update TokenSvc instantiation to use new supportsSecureStorage (2) Test TwoFactorToken methods * PM-5263 - Fix SUPPORTS_SECURE_STORAGE injection token to properly call supportsSecureStorage message * PM-5263 - Token state testing * PM-5263 - TokenState fix name of describe * PM-5263 - TokenService - export TokenStorageLocation for use in tests. * PM-5263 - TokenSvc Tests WIP * PM-5263 - TokenSvc tests - access token logic mostly completed. * PM-5263 - TokenSvc Tests - more WIP - finish testing access token methods. * PM-5263 - TokenSvc WIP - another clear access token test. * PM-5263 - TokenSvc tests - WIP - SetTokens tested. * PM-5263 - Tweak test name * PM-5263 - TokenSvc tests - remove unnecessary describe around 2FA token methods. * PM-5263 - TokenSvc.clearAccessTokenByUserId renamed to just clearAccessToken * PM-5263 - TokenSvc - refactor clearTokens logic and implement individual clear logic which doesn't require vault timeout setting information. * PM-5263 - TokenSvc - Replace all places we have vaultTimeout: number with vaultTimeout: number | null to be accurate. * PM-5263 - TokenSvc.clearTokens - add check for user id; throw if not found * PM-5263 - TokenService - test clearTokens * PM-5263 - TokenSvc Tests - setRefreshToken tested * PM-5263 - TokenSvc tests - getRefreshToken tested + added a new getAccessToken test * PM-5263 - TokenSvc - ClearRefreshToken scenarios tested. * PM-5263 - TokenSvc.clearRefreshToken tests - fix copy pasta * PM-5263 - TokenSvc tests - (1) Fix mistakes in refresh token testing (2) Test setClientId for all scenarios * PM-5263 - TokenSvc tests - (1) Add some getClientId tests (2) clarify lack of awaits * PM-5263 - TokenSvc Tests - WIP - getClientId && clearClientId * PM-5263 - TokenService - getClientSecret - fix error message * PM-5263 - TokenService tests - test all client secret methods * PM-5263 - Update TokenSvc migration to 30th migration * PM-5263 - TokenService - update all tests to initialize data to undefined now that fake state provider supports faking data based on specific key definitions. * PM-5263 - (1) TokenSvc.decodeAccessToken - update static method's error handling (2) TokenSvc tests - test all decodeAccessToken scenarios * PM-5263 - TokenSvc - (1) Add DecodedAccessToken type (2) Refactor getTokenExpirationDate logic to use new type and make proper type checks for numbers for exp claim values. * PM-5263 - TokenSvc tests - test getTokenExpirationDate method. * PM-5263 - TokenSvc - (1) Update DecodedAccessToken docs (2) Tweak naming in tokenSecondsRemaining * PM-5263 - TokenSvc abstraction - add jsdoc for tokenSecondsRemaining * PM-5263 - TokenSvc tests - test tokenSecondsRemaining * PM-5263 - TokenSvc - DecodedAccessToken type - update sstamp info * PM-5263 - TokenService - fix flaky tokenSecondsRemaining tests by locking time * PM-5263 - TokenSvc Tests - Test tokenNeedsRefresh * PM-5263 - (1) TokenSvc - Refactor getUserId to add extra safety (2) TokenSvc tests - test getUserId * PM-5263 - (1) TokenSvc - refactor getUserIdFromAccessToken to handle decoding errors (2) TokenSvc tests - test getUserIdFromAccessToken * PM-5263 - (1) TokenSvc - Refactor getEmail to handle decoding errors + check for specific, expected type (2) TokenSvc tests - test getEmail * PM-5263 - TokenSvc tests - clean up comment * PM-5263 - (1) TokenSvc - getEmailVerified - refactor (2) TokenSvc tests - add getEmailVerified tests * PM-5263 - (1) TokenSvc - refactor getName (2) TokenSvc tests - test getName * PM-5263 - (1) TokenSvc - refactor getIssuer (2) TokenSvc tests - test getIssuer * PM-5263 - TokenSvc - remove unnecessary "as type" statements now that we have a decoded access token type * PM-5263 - (1) TokenSvc - refactor getIsExternal (2) TokenSvc Tests - test getIsExternal * PM-5263 - TokenSvc abstraction - tune up rest of docs. * PM-5263 - TokenSvc - clean up promise<any> and replace with promise<void> * PM-5263 - TokenSvc abstraction - more docs. * PM-5263 - Clean up TODO as I've tested every method in token svc. * PM-5263 - (1) Extract JWT decode logic into auth owned utility function out of the token service (2) Update TokenService decode logic to use new utility function (3) Update LastPassDirectImportService + vault.ts to use new utility function and remove token service dependency. (4) Update tests + migrate tests to new utility test file. * PM-5263 - Rename decodeJwtTokenToJson to decode-jwt-token-to-json to meet lint rules excluding capitals * PM-5263 - TokenSvc + tests - fix all get methods to return undefined like they did before instead of throwing an error if a user id isn't provided. * PM-5263 - Services.module - add missing token service dep * PM-5263 - Update token svc migrations to be 32nd migration * PM-5263 - Popup - Services.module - Remove token service as it no longer requires a background service due to the migration to state provider. The service definition in jslib-services module is enough. * PM-5263 - BaseLoginStrategy - Extract email out of getTwoFactorToken method call for easier debugging. * PM-5263 - Login Comp - Set email into memory on login service so that base login strategy can access user email for looking up 2FA token stored in global state. * PM-5263 - (1) LoginComp - remove loginSvc.setEmail call as no longer necessary + introduced issues w/ popup and background in browser extension (2) AuthReq & Password login strategies now just pass in email to buildTwoFactor method. * PM-5263 - SsoLoginSvc + abstraction - Add key definition and get/set methods for saving user email in session storage so it persists across the SSO redirect. * PM-5263 - Base Login Strategy - BuildTwoFactor - only try to get 2FA token if we have an email to look up their token * PM-5263 - Remove LoginService dependency from LoginStrategyService * PM-5263 - (1) Save off user email when they click enterprise SSO on all clients in login comp (2) Retrieve it and pass it into login strategy in SSO comp * PM-5263 - (1) TokenSvc - update 2FA token methods to be more safe in case user removes record from local storage (2) Add test cases + missing clearTwoFactorToken tests * PM-5263 - Browser SSO login - save user email for browser SSO process * PM-5263 - Finish removing login service from login strategy tests. * PM-5263 - More removals of the login service from the login strategy tests. * PM-5263 - Main.ts - platformUtilsSvc no longer used in TokenSvc so remove it from desktop main.ts * PM-5263 - Fix failing login strategy service tests * PM-5263 - Bump token svc migration values to migration 35 after merging in main * PM-5263 - Bump token svc migration version * PM-5263 - TokenService.clearTwoFactorToken - use delete instead of setting values to null per discussion with Justin Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc + decode JWT token tests - anonymize my information Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - update clear token tests based on actual deletion * PM-5263 - Add docs per PR feedback * PM-5263 - (1) Move ownership of clearing two factor token on rejection from server to base login strategy (2) Each login strategy that supports remember 2FA logic now persists user entered email in its data (3) Base login strategy processTwoFactorResponse now clears 2FA token (4) Updated base login strategy tests to affirm the clearing of the 2FA token * Update libs/auth/src/common/login-strategies/login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-5263 - Login Strategy - per PR feedback, add jsdoc comments to each method I've touched for this PR. * PM-5263 - (1) TokenSvc - adjust setTokens, setAccessToken, setRefreshToken, and clearRefreshToken based on PR feedback to remove optional user ids where possible and improve public interface (2) TokenSvc Abstraction - update docs and abstractions based on removed user ids and changed logic (3) TokenSvc tests - update tests to add new test cases, remove no longer relevant ones, and update test names. * PM-5263 - Bump migrations again --------- Co-authored-by: Matt Gibson <git@mgibson.dev> Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com>
2024-03-15 16:50:04 +01:00
SUPPORTS_SECURE_STORAGE,
SYSTEM_THEME_OBSERVABLE,
SafeInjectionToken,
STATE_FACTORY,
INTRAPROCESS_MESSAGING_SUBJECT,
} from "@bitwarden/angular/services/injection-tokens";
import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module";
[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 { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
[AC-1011] Admin Console / Billing code ownership (#4973) * refactor: move SCIM component to admin-console, refs EC-1011 * refactor: move scimProviderType to admin-console, refs EC-1011 * refactor: move scim-config.api to admin-console, refs EC-1011 * refactor: create models folder and nest existing api contents, refs EC-1011 * refactor: move scim-config to admin-console models, refs EC-1011 * refactor: move billing.component to billing, refs EC-1011 * refactor: remove nested app folder from new billing structure, refs EC-1011 * refactor: move organizations/billing to billing, refs EC-1011 * refactor: move add-credit and adjust-payment to billing/settings, refs EC-1011 * refactor: billing history/sync to billing, refs EC-1011 * refactor: move org plans, payment/method to billing/settings, refs EC-1011 * fix: update legacy file paths for payment-method and tax-info, refs EC-1011 * fix: update imports for scim component, refs EC-1011 * refactor: move subscription and tax-info into billing, refs EC-1011 * refactor: move user-subscription to billing, refs EC-1011 * refactor: move images/cards to billing and update base path, refs EC-1011 * refactor: move payment-method, plan subscription, and plan to billing, refs EC-1011 * refactor: move transaction-type to billing, refs EC-1011 * refactor: move billing-sync-config to billing, refs EC-1011 * refactor: move billing-sync and bit-pay-invoice request to billing, refs EC-1011 * refactor: move org subscription and tax info update requests to billing, refs EC-1011 * fix: broken paths to billing, refs EC-1011 * refactor: move payment request to billing, refs EC-1011 * fix: update remaining imports for payment-request, refs EC-1011 * refactor: move tax-info-update to billing, refs EC-1011 * refactor: move billing-payment, billing-history, and billing responses to billing, refs EC-1011 * refactor: move organization-subscription-responset to billing, refs EC-1011 * refactor: move payment and plan responses to billing, refs EC-1011 * refactor: move subscription response to billing ,refs EC-1011 * refactor: move tax info and rate responses to billing, refs EC-1011 * fix: update remaining path to base response for tax-rate response, refs EC-1011 * refactor: (browser) move organization-service to admin-console, refs EC-1011 * refactor: (browser) move organizaiton-service to admin-console, refs EC-1011 * refactor: (cli) move share command to admin-console, refs EC-1011 * refactor: move organization-collect request model to admin-console, refs EC-1011 * refactor: (web) move organization, collection/user responses to admin-console, refs EC-1011 * refactor: (cli) move selection-read-only to admin-console, refs EC-1011 * refactor: (desktop) move organization-filter to admin-console, refs EC-1011 * refactor: (web) move organization-switcher to admin-console, refs EC-1011 * refactor: (web) move access-selector to admin-console, refs EC-1011 * refactor: (web) move create folder to admin-console, refs EC-1011 * refactor: (web) move org guards folder to admin-console, refs EC-1011 * refactor: (web) move org layout to admin-console, refs EC-1011 * refactor: move manage collections to admin console, refs EC-1011 * refactor: (web) move collection-dialog to admin-console, refs EC-1011 * refactor: (web) move entity users/events and events component to admin-console, refs EC-1011 * refactor: (web) move groups/group-add-edit to admin-console, refs EC-1011 * refactor: (web) move manage, org-manage module, and user-confirm to admin-console, refs EC-1011 * refactor: (web) move people to admin-console, refs EC-1011 * refactor: (web) move reset-password to admin-console, refs EC-1011 * refactor: (web) move organization-routing and module to admin-console, refs EC-1011 * refactor: move admin-console and billing within app scope, refs EC-1011 * fix: update leftover merge conflicts, refs EC-1011 * refactor: (web) member-dialog to admin-console, refs EC-1011 * refactor: (web) move policies to admin-console, refs EC-1011 * refactor: (web) move reporting to admin-console, refs EC-1011 * refactor: (web) move settings to admin-console, refs EC-1011 * refactor: (web) move sponsorships to admin-console, refs EC-1011 * refactor: (web) move tools to admin-console, refs EC-1011 * refactor: (web) move users to admin-console, refs EC-1011 * refactor: (web) move collections to admin-console, refs EC-1011 * refactor: (web) move create-organization to admin-console, refs EC-1011 * refactor: (web) move licensed components to admin-console, refs EC-1011 * refactor: (web) move bit organization modules to admin-console, refs EC-1011 * fix: update leftover import statements for organizations.module, refs EC-1011 * refactor: (web) move personal vault and max timeout to admin-console, refs EC-1011 * refactor: (web) move providers to admin-console, refs EC-1011 * refactor: (libs) move organization service to admin-console, refs EC-1011 * refactor: (libs) move profile org/provider responses and other misc org responses to admin-console, refs EC-1011 * refactor: (libs) move provider request and selectionion-read-only request to admin-console, refs EC-1011 * fix: update missed import path for provider-user-update request, refs EC-1011 * refactor: (libs) move abstractions to admin-console, refs EC-1011 * refactor: (libs) move org/provider enums to admin-console, refs EC-1011 * fix: update downstream import statements from libs changes, refs EC-1011 * refactor: (libs) move data files to admin-console, refs EC-1011 * refactor: (libs) move domain to admin-console, refs EC-1011 * refactor: (libs) move request objects to admin-console, refs EC-1011 * fix: update downstream import changes from libs, refs EC-1011 * refactor: move leftover provider files to admin-console, refs EC-1011 * refactor: (browser) move group policy environment to admin-console, refs EC-1011 * fix: (browser) update downstream import statements, refs EC-1011 * fix: (desktop) update downstream libs moves, refs EC-1011 * fix: (cli) update downstream import changes from libs, refs EC-1011 * refactor: move org-auth related files to admin-console, refs EC-1011 * refactor: (libs) move request objects to admin-console, refs EC-1011 * refactor: move persmissions to admin-console, refs EC-1011 * refactor: move sponsored families to admin-console and fix libs changes, refs EC-1011 * refactor: move collections to admin-console, refs EC-1011 * refactor: move spec file back to spec scope, refs EC-1011 * fix: update downstream imports due to libs changes, refs EC-1011 * fix: udpate downstream import changes due to libs, refs EC-1011 * fix: update downstream imports due to libs changes, refs EC-1011 * fix: update downstream imports from libs changes, refs EC-1011 * fix: update path malformation in jslib-services.module, refs EC-1011 * fix: lint errors from improper casing, refs AC-1011 * fix: update downstream filename changes, refs AC-1011 * fix: (cli) update downstream filename changes, refs AC-1011 * fix: (desktop) update downstream filename changes, refs AC-1011 * fix: (browser) update downstream filename changes, refs AC-1011 * fix: lint errors, refs AC-1011 * fix: prettier, refs AC-1011 * fix: lint fixes for import order, refs AC-1011 * fix: update import path for provider user type, refs AC-1011 * fix: update new codes import paths for admin console structure, refs AC-1011 * fix: lint/prettier, refs AC-1011 * fix: update layout stories path, refs AC-1011 * fix: update comoponents card icons base variable in styles, refs AC-1011 * fix: update provider service path in permissions guard spec, refs AC-1011 * fix: update provider permission guard path, refs AC-1011 * fix: remove unecessary TODO for shared index export statement, refs AC-1011 * refactor: move browser-organization service and cli organization-user response out of admin-console, refs AC-1011 * refactor: move web/browser/desktop collections component to vault domain, refs AC-1011 * refactor: move organization.module out of admin-console scope, refs AC-1011 * fix: prettier, refs AC-1011 * refactor: move organizations-api-key.request out of admin-console scope, refs AC-1011
2023-03-22 16:03:50 +01:00
import { PolicyService as PolicyServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
Expand account service (#6622) * Define account service observable responsibilities * Establish account service observables and update methods * Update Account Service observables from state service This is a temporary stop-gap to avoid needing to reroute all account activity and status changes through the account service. That can be done as part of the breakup of state service. * Add matchers for Observable emissions * Fix null active account * Test account service * Transition account status to account info * Remove unused matchers * Remove duplicate class * Replay active account for late subscriptions * Add factories for background services * Fix state service for web * Allow for optional messaging This is a temporary hack until the flow of account status can be reversed from state -> account to account -> state. The foreground account service will still logout, it's just the background one cannot send messages * Fix add account logic * Do not throw on recoverable errors It's possible that duplicate entries exist in `activeAccounts` exist in the wild. If we throw on adding a duplicate account this will cause applications to be unusable until duplicates are removed it is not necessary to throw since this is recoverable. with some potential loss in current account status * Add documentation to abstraction * Update libs/common/spec/utils.ts Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * Fix justin's comment :fist-shake: --------- Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2023-10-19 21:41:01 +02:00
import { AccountService as AccountServiceAbstraction } from "@bitwarden/common/auth/abstractions/account.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 as AuthServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth.service";
import { KdfConfigService as KdfConfigServiceAbstraction } from "@bitwarden/common/auth/abstractions/kdf-config.service";
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction";
Auth/PM-5263 - TokenService State Provider Migration (#7975) * PM-5263 - Token Service state migration - (1) Got key and state definitions setup (2) Ported over core state service getTimeoutBasedStorageOptions method logic into local determineStorageLocation method (3) Updated majority of methods to use state provider state * PM-5263 - StateSvc - add TODO to remove timeoutBasedStorageOptions + other state methods after migration code complete. * PM-5263 - TokenSvc - ClearToken method - (1) Update signature to remove user id as it wasn't used and it simplifies the new state provider implementation (2) Convert away from state svc to state provider state. * PM-5263 - TokenService - update deps - WIP on circular dep issues. * PM-5263 - To resolve circular dep issues between VaultTimeoutSettingsSvc and TokenService: (1) For writes, require callers to pass in vault timeout data (2) For reads, we can just check both locations. This approach has 1 less state call than the previous implementation and is safe as long as the clear logic properly works and is executed anytime a user changes their vault timeout action (lock or log out) & vault timeout (numeric value) * PM-5263 - VaultTimeoutSettingsSvc - Set token calls now updated to include vault timeout info. * PM-5263 - Update API Service - add state service and look up vault timeout details and pass to token service when setting token info. * PM-5263 - TokenService - update service dependencies. * PM-5263 - TokenService - Add new getAccessTokenByUserId method for state service use case. * PM-5263 - StateSvc - remove migrated methods and try to replace all usages of getAccessToken. WIP * PM-5263 - TokenSvc Migration - start on migrator * PM-5263 - (1) TokenSvc - Build new clearAccessTokenByUserId which is required by state service (2) TokenSvc - Update getToken to take an optional userId to handle another state service case (3) Add some documentation to TokenSvc abstraction. * PM-5263 - StateService - finish updating all calls within the state service which accessed token service state directly with calls to the new token service methods instead. * PM-5263 - TokenSvc Abstraction - Add more docs * PM-5263 - TokenSvc abstraction - more doc tweaks * PM-5263 - Web state service - add new token service dependency. * PM-5263 - User API Key Login Strategy - Update to pull vault timeout action and vault timeout from state service in order to pass to new token service endpoints for setting API key client id and secret. * PM-5263 - (1) Remove TokenSvc owned state from account (2) StateSvc - remove account scaffold logic for clearing removed account data. The same functionality will exist in the state provider framework via lifecycle hooks cleaning up this data and users getting initialized with null data by default. * PM-5263 - Add token service dependency to state service (WIP - desktop deps not working) * PM-5263 - Update services module on desktop and browser to add token svc dependency * PM-5263 - API service factory - add state service factory dependency that I missed initially to get browser building. * PM-5263 - TokenSvc - getToken/setToken/decodeToken --> getAccessToken/setAccessToken/decodeAccessToken * PM-5263 - TokenSvc State Provider Migrator - WIP - update expected acct type to match actual account * PM-5263 - TokenService - clearToken renamed to clearTokens * PM-5263 - CLI - NodeApiService - add state service dep to get CLI building. * PM-5263 - StateDefinitions - use unique state definition names * PM-5263 - StateSvc - remove getTimeoutBasedStorageOptions as no longer used. * PM-5263 - TokenSvc - Add TODO for figuring out how to store tokens in secure storage. * PM-5263 - StateSvc - remove get/set 2FA token - references migrated later. * PM-5263 - TODO: figure out if using same key definition names is an issue * PM-5263 - TokenServiceStateProviderMigrator written * PM-5263 - TokenServiceStateProviderMigrator - (1) Don't update legacy account if we only added a new state in state provider for 2FA token (2) Use for loop for easier debugging * PM-5263 - TokenServiceStateProviderMigrator test - WIP - migration testing mostly complete and passing. Rollback logic TODO. * PM-5263 - TokenServiceStateProviderMigrator - Add rollback logic to restore 2FA token from users to global. * PM-5263 - TokenServiceStateProviderMigrator - Refactor rollback to only set account once as not necessary to set it every time. * PM-5263 - TokenServiceStateProviderMigrator tests - test all rollback scenarios * PM-5263 - Remove TODO as don't need unique key def names as long as state def keys are unique. * PM-5263 - TokenSvc - update clearAccessTokenByUserId to use proper state provider helper method to set state. * PM-5263 - Revert accidentally committing settings.json changes. * PM-5263 - TokenSvc - update all 2FA token methods to require email so we can user specifically scope 2FA tokens while still storing them in global storage. * PM-5263 - Update all token service 2FA set / get / clear methods to pass in email. * PM-5263 - JslibServices module - add missed login service to login strategy svc deps. * PM-5263 - VaultTimeoutSettingsService - setVaultTimeoutOptions - rename token to accesToken for clarity. * PM-5263 - (1) TokenSvc - remove getAccessTokenByUserId and force consumers to use getAccessToken w/ optional user id to keep interface small (2) TokenSvc - attempt to implement secure storage on platforms that support it for access & refresh token storage (3) StateSvc - replace usage of getAccessTokenByUserId with getAccessToken * PM-5263 - TokenSvc - add platform utils and secure storage svc deps * PM-5263 - TODO: figure out what to do with broken migration * PM-5263 - TODO: update tests in light of latest 2FA token changes. * PM-5263 - TokenSvc - clean up TODO * PM-5263 - We should have tests for the token service. * PM-5263 - TokenSvc - setAccessToken - If platform supports secure storage and we are saving an access token, remove the access token from memory and disk to fully migrate to secure storage. * PM-5263 - TokenSvc - getAccessToken - Update logic to look at memory and disk first always and secure storage last to support the secure storage migration * PM-5263 - TokenSvc - setAccesToken - if user id null on a secure storage supporting platform, throw error. * PM-5263 - TokenService - (1) Refresh token now stored in secure storage (2) Refresh token set now private as we require a user id to store it in secure storage and we can use the setTokens method to enforce always setting the access token and refresh token together in order to extract a user id from the refresh token. (3) setTokens clientIdClientSecret param now optional * PM-5263 - TokenServiceStateProviderMigrator - update migration to take global but user scoped 2FA token storage changes into account. * PM-5263 - Remove old migration as it references state we are removing. Bump min version. Co-authored-by: Matt Gibson <git@mgibson.dev> * PM-5263 - TokenService - 2FA token methods now backed by global state record which maps email to individual tokens. * PM-5263 - WIP on Token Svc migrator and test updates based on new 2FA token storage changes. * PM-5263 - TokenSvc - (1) Add jira tickets to clean up state migration (2) Add state to track secure storage migration to improve # of reads to get data * PM-5263 - StateDef - consolidate name of token domain state defs per feedback from Justin + update migration tests * PM-5263 - TokenSvc - fix error message and add TODO * PM-5263 - Update token service migration + tests to pass after all 2FA token changes. * PM-5263 - Fix all login strategy tests which were failing due to token state provider changes + the addition of the loginService as a dependency in the base login strategy. * PM-5263 - Register TokenService state provider migration with migrator * PM-5263 - TokenSvc state migration - set tokens after initializing account * PM-5263 - TokenService changes - WIP - convert from ActiveUserStateProvider to just SingleUserStateProvider to avoid future circ dependency issues. Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> * PM-5263 - TokenSvc - create getSecureStorageOptions for centralizing all logic for getting data out of SecureStorage. * PM-5263 - TokenSvc - (1) Refactor determineStorageLocation to also determine secure storage - created a TokenStorageLocation string enum to remove magic strings (2) Refactor setAccessToken to use switch (3) Refactor clearAccessTokenByUserId to clear all locations and not early return on secure storage b/c we only use secure storage if disk is the location but I don't want to require vault timeout data for this method. * PM-5263 - TokenSvc - getDataFromSecureStorage - Refactor to be more generic for easier re-use * PM-5263 - TokenSvc - Convert refresh token methods to use single user state and require user ids * PM-5263 - VaultTimeoutSettingsSvc - get user id and pass to access and refresh token methods. * PM-5263 - TokenSvc - refactor save secure storage logic into private helper. * PM-5263 - Base Login Strategy - per discussion with Justin, move save of tokens to before account initialization as we can always derive the user id from the access token. This will ensure that the account is initialized with the proper authN status. * PM-5263 - TokenSvc - latest refactor - update all methods to accept optional userId now as we can read active user id from global state provider without using activeUserStateProvider (thus, avoiding a circular dep and having to have every method accept in a mandatory user id). * PM-5263 - VaultTimeoutSettingsService - remove user id from token calls * PM-5263 - TokenSvc - update all places we instantiate token service to properly pass in new deps. * PM-5263 - TokenSvc migration is now 27th instead of 23rd. * PM-5263 - Browser - MainContextMenuHandler - Update service options to include PlatformUtilsServiceInitOptions as the TokenService requires that and the TokenService is now injected on the StateService * PM-5263 - TokenSvc migration test - update rollback tests to start with correct current version * PM-5263 - Create token service test file - WIP * PM-5263 - TokenSvc - tests WIP - instantiates working. * PM-5263 - TokenSvc - set2FAToken - use null coalesce to ensure record is instantiated for new users before setting data on it. * PM-5263 - TokenService tests - WIP - 2FA token tests. * PM-5263 - Worked with Justin to resolve desktop circular dependency issue by adding SUPPORTS_SECURE_STORAGE injection token instead of injecting PlatformUtilsService directly into TokenService. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - WIP - (1) Update TokenSvc instantiation to use new supportsSecureStorage (2) Test TwoFactorToken methods * PM-5263 - Fix SUPPORTS_SECURE_STORAGE injection token to properly call supportsSecureStorage message * PM-5263 - Token state testing * PM-5263 - TokenState fix name of describe * PM-5263 - TokenService - export TokenStorageLocation for use in tests. * PM-5263 - TokenSvc Tests WIP * PM-5263 - TokenSvc tests - access token logic mostly completed. * PM-5263 - TokenSvc Tests - more WIP - finish testing access token methods. * PM-5263 - TokenSvc WIP - another clear access token test. * PM-5263 - TokenSvc tests - WIP - SetTokens tested. * PM-5263 - Tweak test name * PM-5263 - TokenSvc tests - remove unnecessary describe around 2FA token methods. * PM-5263 - TokenSvc.clearAccessTokenByUserId renamed to just clearAccessToken * PM-5263 - TokenSvc - refactor clearTokens logic and implement individual clear logic which doesn't require vault timeout setting information. * PM-5263 - TokenSvc - Replace all places we have vaultTimeout: number with vaultTimeout: number | null to be accurate. * PM-5263 - TokenSvc.clearTokens - add check for user id; throw if not found * PM-5263 - TokenService - test clearTokens * PM-5263 - TokenSvc Tests - setRefreshToken tested * PM-5263 - TokenSvc tests - getRefreshToken tested + added a new getAccessToken test * PM-5263 - TokenSvc - ClearRefreshToken scenarios tested. * PM-5263 - TokenSvc.clearRefreshToken tests - fix copy pasta * PM-5263 - TokenSvc tests - (1) Fix mistakes in refresh token testing (2) Test setClientId for all scenarios * PM-5263 - TokenSvc tests - (1) Add some getClientId tests (2) clarify lack of awaits * PM-5263 - TokenSvc Tests - WIP - getClientId && clearClientId * PM-5263 - TokenService - getClientSecret - fix error message * PM-5263 - TokenService tests - test all client secret methods * PM-5263 - Update TokenSvc migration to 30th migration * PM-5263 - TokenService - update all tests to initialize data to undefined now that fake state provider supports faking data based on specific key definitions. * PM-5263 - (1) TokenSvc.decodeAccessToken - update static method's error handling (2) TokenSvc tests - test all decodeAccessToken scenarios * PM-5263 - TokenSvc - (1) Add DecodedAccessToken type (2) Refactor getTokenExpirationDate logic to use new type and make proper type checks for numbers for exp claim values. * PM-5263 - TokenSvc tests - test getTokenExpirationDate method. * PM-5263 - TokenSvc - (1) Update DecodedAccessToken docs (2) Tweak naming in tokenSecondsRemaining * PM-5263 - TokenSvc abstraction - add jsdoc for tokenSecondsRemaining * PM-5263 - TokenSvc tests - test tokenSecondsRemaining * PM-5263 - TokenSvc - DecodedAccessToken type - update sstamp info * PM-5263 - TokenService - fix flaky tokenSecondsRemaining tests by locking time * PM-5263 - TokenSvc Tests - Test tokenNeedsRefresh * PM-5263 - (1) TokenSvc - Refactor getUserId to add extra safety (2) TokenSvc tests - test getUserId * PM-5263 - (1) TokenSvc - refactor getUserIdFromAccessToken to handle decoding errors (2) TokenSvc tests - test getUserIdFromAccessToken * PM-5263 - (1) TokenSvc - Refactor getEmail to handle decoding errors + check for specific, expected type (2) TokenSvc tests - test getEmail * PM-5263 - TokenSvc tests - clean up comment * PM-5263 - (1) TokenSvc - getEmailVerified - refactor (2) TokenSvc tests - add getEmailVerified tests * PM-5263 - (1) TokenSvc - refactor getName (2) TokenSvc tests - test getName * PM-5263 - (1) TokenSvc - refactor getIssuer (2) TokenSvc tests - test getIssuer * PM-5263 - TokenSvc - remove unnecessary "as type" statements now that we have a decoded access token type * PM-5263 - (1) TokenSvc - refactor getIsExternal (2) TokenSvc Tests - test getIsExternal * PM-5263 - TokenSvc abstraction - tune up rest of docs. * PM-5263 - TokenSvc - clean up promise<any> and replace with promise<void> * PM-5263 - TokenSvc abstraction - more docs. * PM-5263 - Clean up TODO as I've tested every method in token svc. * PM-5263 - (1) Extract JWT decode logic into auth owned utility function out of the token service (2) Update TokenService decode logic to use new utility function (3) Update LastPassDirectImportService + vault.ts to use new utility function and remove token service dependency. (4) Update tests + migrate tests to new utility test file. * PM-5263 - Rename decodeJwtTokenToJson to decode-jwt-token-to-json to meet lint rules excluding capitals * PM-5263 - TokenSvc + tests - fix all get methods to return undefined like they did before instead of throwing an error if a user id isn't provided. * PM-5263 - Services.module - add missing token service dep * PM-5263 - Update token svc migrations to be 32nd migration * PM-5263 - Popup - Services.module - Remove token service as it no longer requires a background service due to the migration to state provider. The service definition in jslib-services module is enough. * PM-5263 - BaseLoginStrategy - Extract email out of getTwoFactorToken method call for easier debugging. * PM-5263 - Login Comp - Set email into memory on login service so that base login strategy can access user email for looking up 2FA token stored in global state. * PM-5263 - (1) LoginComp - remove loginSvc.setEmail call as no longer necessary + introduced issues w/ popup and background in browser extension (2) AuthReq & Password login strategies now just pass in email to buildTwoFactor method. * PM-5263 - SsoLoginSvc + abstraction - Add key definition and get/set methods for saving user email in session storage so it persists across the SSO redirect. * PM-5263 - Base Login Strategy - BuildTwoFactor - only try to get 2FA token if we have an email to look up their token * PM-5263 - Remove LoginService dependency from LoginStrategyService * PM-5263 - (1) Save off user email when they click enterprise SSO on all clients in login comp (2) Retrieve it and pass it into login strategy in SSO comp * PM-5263 - (1) TokenSvc - update 2FA token methods to be more safe in case user removes record from local storage (2) Add test cases + missing clearTwoFactorToken tests * PM-5263 - Browser SSO login - save user email for browser SSO process * PM-5263 - Finish removing login service from login strategy tests. * PM-5263 - More removals of the login service from the login strategy tests. * PM-5263 - Main.ts - platformUtilsSvc no longer used in TokenSvc so remove it from desktop main.ts * PM-5263 - Fix failing login strategy service tests * PM-5263 - Bump token svc migration values to migration 35 after merging in main * PM-5263 - Bump token svc migration version * PM-5263 - TokenService.clearTwoFactorToken - use delete instead of setting values to null per discussion with Justin Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc + decode JWT token tests - anonymize my information Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - update clear token tests based on actual deletion * PM-5263 - Add docs per PR feedback * PM-5263 - (1) Move ownership of clearing two factor token on rejection from server to base login strategy (2) Each login strategy that supports remember 2FA logic now persists user entered email in its data (3) Base login strategy processTwoFactorResponse now clears 2FA token (4) Updated base login strategy tests to affirm the clearing of the 2FA token * Update libs/auth/src/common/login-strategies/login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-5263 - Login Strategy - per PR feedback, add jsdoc comments to each method I've touched for this PR. * PM-5263 - (1) TokenSvc - adjust setTokens, setAccessToken, setRefreshToken, and clearRefreshToken based on PR feedback to remove optional user ids where possible and improve public interface (2) TokenSvc Abstraction - update docs and abstractions based on removed user ids and changed logic (3) TokenSvc tests - update tests to add new test cases, remove no longer relevant ones, and update test names. * PM-5263 - Bump migrations again --------- Co-authored-by: Matt Gibson <git@mgibson.dev> Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com>
2024-03-15 16:50:04 +01:00
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
2024-02-28 17:49:20 +01:00
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service";
import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service";
import { KeyGenerationService as KeyGenerationServiceAbstraction } from "@bitwarden/common/platform/abstractions/key-generation.service";
import {
LogService,
LogService as LogServiceAbstraction,
} from "@bitwarden/common/platform/abstractions/log.service";
import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/platform/abstractions/messaging.service";
import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service";
import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service";
import { SystemService as SystemServiceAbstraction } from "@bitwarden/common/platform/abstractions/system.service";
import { BiometricStateService } from "@bitwarden/common/platform/biometrics/biometric-state.service";
import { StateFactory } from "@bitwarden/common/platform/factories/state-factory";
import { Message, MessageListener, MessageSender } from "@bitwarden/common/platform/messaging";
// eslint-disable-next-line no-restricted-imports -- Used for dependency injection
import { SubjectMessageSender } from "@bitwarden/common/platform/messaging/internal";
import { GlobalState } from "@bitwarden/common/platform/models/domain/global-state";
import { MemoryStorageService } from "@bitwarden/common/platform/services/memory-storage.service";
import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner";
import { SystemService } from "@bitwarden/common/platform/services/system.service";
import { GlobalStateProvider, StateProvider } from "@bitwarden/common/platform/state";
// eslint-disable-next-line import/no-restricted-paths -- Implementation for memory storage
import { MemoryStorageService as MemoryStorageServiceForStateProviders } from "@bitwarden/common/platform/state/storage/memory-storage.service";
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
[SG-998] and [SG-999] Vault and Autofill team refactor (#4542) * Move DeprecatedVaultFilterService to vault folder * [libs] move VaultItemsComponent * [libs] move AddEditComponent * [libs] move AddEditCustomFields * [libs] move attachmentsComponent * [libs] folderAddEditComponent * [libs] IconComponent * [libs] PasswordRepormptComponent * [libs] PremiumComponent * [libs] ViewCustomFieldsComponent * [libs] ViewComponent * [libs] PasswordRepromptService * [libs] Move FolderService and FolderApiService abstractions * [libs] FolderService imports * [libs] PasswordHistoryComponent * [libs] move Sync and SyncNotifier abstractions * [libs] SyncService imports * [libs] fix file casing for passwordReprompt abstraction * [libs] SyncNotifier import fix * [libs] CipherServiceAbstraction * [libs] PasswordRepromptService abstraction * [libs] Fix file casing for angular passwordReprompt service * [libs] fix file casing for SyncNotifierService * [libs] CipherRepromptType * [libs] rename CipherRepromptType * [libs] CipherType * [libs] Rename CipherType * [libs] CipherData * [libs] FolderData * [libs] PasswordHistoryData * [libs] AttachmentData * [libs] CardData * [libs] FieldData * [libs] IdentityData * [libs] LocalData * [libs] LoginData * [libs] SecureNoteData * [libs] LoginUriData * [libs] Domain classes * [libs] SecureNote * [libs] Request models * [libs] Response models * [libs] View part 1 * [libs] Views part 2 * [libs] Move folder services * [libs] Views fixes * [libs] Move sync services * [libs] cipher service * [libs] Types * [libs] Sync file casing * [libs] Fix folder service import * [libs] Move spec files * [libs] casing fixes on spec files * [browser] Autofill background, clipboard, commands * [browser] Fix ContextMenusBackground casing * [browser] Rename fix * [browser] Autofill content * [browser] autofill.js * [libs] enpass importer spec fix * [browser] autofill models * [browser] autofill manifest path updates * [browser] Autofill notification files * [browser] autofill services * [browser] Fix file casing * [browser] Vault popup loose components * [browser] Vault components * [browser] Manifest fixes * [browser] Vault services * [cli] vault commands and models * [browser] File capitilization fixes * [desktop] Vault components and services * [web] vault loose components * [web] Vault components * [browser] Fix misc-utils import * [libs] Fix psono spec imports * [fix] Add comments to address lint rules
2023-01-31 22:08:37 +01:00
import { CipherService as CipherServiceAbstraction } from "@bitwarden/common/vault/abstractions/cipher.service";
import { DialogService } from "@bitwarden/components";
2024-04-05 21:38:10 +02:00
import { PinServiceAbstraction } from "../../../../../libs/auth/src/common/abstractions";
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 { LoginGuard } from "../../auth/guards/login.guard";
import { DesktopAutofillSettingsService } from "../../autofill/services/desktop-autofill-settings.service";
import { Account } from "../../models/account";
import { DesktopSettingsService } from "../../platform/services/desktop-settings.service";
import { ElectronCryptoService } from "../../platform/services/electron-crypto.service";
import { ElectronLogRendererService } from "../../platform/services/electron-log.renderer.service";
Auth/PM-5263 - TokenService State Provider Migration (#7975) * PM-5263 - Token Service state migration - (1) Got key and state definitions setup (2) Ported over core state service getTimeoutBasedStorageOptions method logic into local determineStorageLocation method (3) Updated majority of methods to use state provider state * PM-5263 - StateSvc - add TODO to remove timeoutBasedStorageOptions + other state methods after migration code complete. * PM-5263 - TokenSvc - ClearToken method - (1) Update signature to remove user id as it wasn't used and it simplifies the new state provider implementation (2) Convert away from state svc to state provider state. * PM-5263 - TokenService - update deps - WIP on circular dep issues. * PM-5263 - To resolve circular dep issues between VaultTimeoutSettingsSvc and TokenService: (1) For writes, require callers to pass in vault timeout data (2) For reads, we can just check both locations. This approach has 1 less state call than the previous implementation and is safe as long as the clear logic properly works and is executed anytime a user changes their vault timeout action (lock or log out) & vault timeout (numeric value) * PM-5263 - VaultTimeoutSettingsSvc - Set token calls now updated to include vault timeout info. * PM-5263 - Update API Service - add state service and look up vault timeout details and pass to token service when setting token info. * PM-5263 - TokenService - update service dependencies. * PM-5263 - TokenService - Add new getAccessTokenByUserId method for state service use case. * PM-5263 - StateSvc - remove migrated methods and try to replace all usages of getAccessToken. WIP * PM-5263 - TokenSvc Migration - start on migrator * PM-5263 - (1) TokenSvc - Build new clearAccessTokenByUserId which is required by state service (2) TokenSvc - Update getToken to take an optional userId to handle another state service case (3) Add some documentation to TokenSvc abstraction. * PM-5263 - StateService - finish updating all calls within the state service which accessed token service state directly with calls to the new token service methods instead. * PM-5263 - TokenSvc Abstraction - Add more docs * PM-5263 - TokenSvc abstraction - more doc tweaks * PM-5263 - Web state service - add new token service dependency. * PM-5263 - User API Key Login Strategy - Update to pull vault timeout action and vault timeout from state service in order to pass to new token service endpoints for setting API key client id and secret. * PM-5263 - (1) Remove TokenSvc owned state from account (2) StateSvc - remove account scaffold logic for clearing removed account data. The same functionality will exist in the state provider framework via lifecycle hooks cleaning up this data and users getting initialized with null data by default. * PM-5263 - Add token service dependency to state service (WIP - desktop deps not working) * PM-5263 - Update services module on desktop and browser to add token svc dependency * PM-5263 - API service factory - add state service factory dependency that I missed initially to get browser building. * PM-5263 - TokenSvc - getToken/setToken/decodeToken --> getAccessToken/setAccessToken/decodeAccessToken * PM-5263 - TokenSvc State Provider Migrator - WIP - update expected acct type to match actual account * PM-5263 - TokenService - clearToken renamed to clearTokens * PM-5263 - CLI - NodeApiService - add state service dep to get CLI building. * PM-5263 - StateDefinitions - use unique state definition names * PM-5263 - StateSvc - remove getTimeoutBasedStorageOptions as no longer used. * PM-5263 - TokenSvc - Add TODO for figuring out how to store tokens in secure storage. * PM-5263 - StateSvc - remove get/set 2FA token - references migrated later. * PM-5263 - TODO: figure out if using same key definition names is an issue * PM-5263 - TokenServiceStateProviderMigrator written * PM-5263 - TokenServiceStateProviderMigrator - (1) Don't update legacy account if we only added a new state in state provider for 2FA token (2) Use for loop for easier debugging * PM-5263 - TokenServiceStateProviderMigrator test - WIP - migration testing mostly complete and passing. Rollback logic TODO. * PM-5263 - TokenServiceStateProviderMigrator - Add rollback logic to restore 2FA token from users to global. * PM-5263 - TokenServiceStateProviderMigrator - Refactor rollback to only set account once as not necessary to set it every time. * PM-5263 - TokenServiceStateProviderMigrator tests - test all rollback scenarios * PM-5263 - Remove TODO as don't need unique key def names as long as state def keys are unique. * PM-5263 - TokenSvc - update clearAccessTokenByUserId to use proper state provider helper method to set state. * PM-5263 - Revert accidentally committing settings.json changes. * PM-5263 - TokenSvc - update all 2FA token methods to require email so we can user specifically scope 2FA tokens while still storing them in global storage. * PM-5263 - Update all token service 2FA set / get / clear methods to pass in email. * PM-5263 - JslibServices module - add missed login service to login strategy svc deps. * PM-5263 - VaultTimeoutSettingsService - setVaultTimeoutOptions - rename token to accesToken for clarity. * PM-5263 - (1) TokenSvc - remove getAccessTokenByUserId and force consumers to use getAccessToken w/ optional user id to keep interface small (2) TokenSvc - attempt to implement secure storage on platforms that support it for access & refresh token storage (3) StateSvc - replace usage of getAccessTokenByUserId with getAccessToken * PM-5263 - TokenSvc - add platform utils and secure storage svc deps * PM-5263 - TODO: figure out what to do with broken migration * PM-5263 - TODO: update tests in light of latest 2FA token changes. * PM-5263 - TokenSvc - clean up TODO * PM-5263 - We should have tests for the token service. * PM-5263 - TokenSvc - setAccessToken - If platform supports secure storage and we are saving an access token, remove the access token from memory and disk to fully migrate to secure storage. * PM-5263 - TokenSvc - getAccessToken - Update logic to look at memory and disk first always and secure storage last to support the secure storage migration * PM-5263 - TokenSvc - setAccesToken - if user id null on a secure storage supporting platform, throw error. * PM-5263 - TokenService - (1) Refresh token now stored in secure storage (2) Refresh token set now private as we require a user id to store it in secure storage and we can use the setTokens method to enforce always setting the access token and refresh token together in order to extract a user id from the refresh token. (3) setTokens clientIdClientSecret param now optional * PM-5263 - TokenServiceStateProviderMigrator - update migration to take global but user scoped 2FA token storage changes into account. * PM-5263 - Remove old migration as it references state we are removing. Bump min version. Co-authored-by: Matt Gibson <git@mgibson.dev> * PM-5263 - TokenService - 2FA token methods now backed by global state record which maps email to individual tokens. * PM-5263 - WIP on Token Svc migrator and test updates based on new 2FA token storage changes. * PM-5263 - TokenSvc - (1) Add jira tickets to clean up state migration (2) Add state to track secure storage migration to improve # of reads to get data * PM-5263 - StateDef - consolidate name of token domain state defs per feedback from Justin + update migration tests * PM-5263 - TokenSvc - fix error message and add TODO * PM-5263 - Update token service migration + tests to pass after all 2FA token changes. * PM-5263 - Fix all login strategy tests which were failing due to token state provider changes + the addition of the loginService as a dependency in the base login strategy. * PM-5263 - Register TokenService state provider migration with migrator * PM-5263 - TokenSvc state migration - set tokens after initializing account * PM-5263 - TokenService changes - WIP - convert from ActiveUserStateProvider to just SingleUserStateProvider to avoid future circ dependency issues. Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> * PM-5263 - TokenSvc - create getSecureStorageOptions for centralizing all logic for getting data out of SecureStorage. * PM-5263 - TokenSvc - (1) Refactor determineStorageLocation to also determine secure storage - created a TokenStorageLocation string enum to remove magic strings (2) Refactor setAccessToken to use switch (3) Refactor clearAccessTokenByUserId to clear all locations and not early return on secure storage b/c we only use secure storage if disk is the location but I don't want to require vault timeout data for this method. * PM-5263 - TokenSvc - getDataFromSecureStorage - Refactor to be more generic for easier re-use * PM-5263 - TokenSvc - Convert refresh token methods to use single user state and require user ids * PM-5263 - VaultTimeoutSettingsSvc - get user id and pass to access and refresh token methods. * PM-5263 - TokenSvc - refactor save secure storage logic into private helper. * PM-5263 - Base Login Strategy - per discussion with Justin, move save of tokens to before account initialization as we can always derive the user id from the access token. This will ensure that the account is initialized with the proper authN status. * PM-5263 - TokenSvc - latest refactor - update all methods to accept optional userId now as we can read active user id from global state provider without using activeUserStateProvider (thus, avoiding a circular dep and having to have every method accept in a mandatory user id). * PM-5263 - VaultTimeoutSettingsService - remove user id from token calls * PM-5263 - TokenSvc - update all places we instantiate token service to properly pass in new deps. * PM-5263 - TokenSvc migration is now 27th instead of 23rd. * PM-5263 - Browser - MainContextMenuHandler - Update service options to include PlatformUtilsServiceInitOptions as the TokenService requires that and the TokenService is now injected on the StateService * PM-5263 - TokenSvc migration test - update rollback tests to start with correct current version * PM-5263 - Create token service test file - WIP * PM-5263 - TokenSvc - tests WIP - instantiates working. * PM-5263 - TokenSvc - set2FAToken - use null coalesce to ensure record is instantiated for new users before setting data on it. * PM-5263 - TokenService tests - WIP - 2FA token tests. * PM-5263 - Worked with Justin to resolve desktop circular dependency issue by adding SUPPORTS_SECURE_STORAGE injection token instead of injecting PlatformUtilsService directly into TokenService. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - WIP - (1) Update TokenSvc instantiation to use new supportsSecureStorage (2) Test TwoFactorToken methods * PM-5263 - Fix SUPPORTS_SECURE_STORAGE injection token to properly call supportsSecureStorage message * PM-5263 - Token state testing * PM-5263 - TokenState fix name of describe * PM-5263 - TokenService - export TokenStorageLocation for use in tests. * PM-5263 - TokenSvc Tests WIP * PM-5263 - TokenSvc tests - access token logic mostly completed. * PM-5263 - TokenSvc Tests - more WIP - finish testing access token methods. * PM-5263 - TokenSvc WIP - another clear access token test. * PM-5263 - TokenSvc tests - WIP - SetTokens tested. * PM-5263 - Tweak test name * PM-5263 - TokenSvc tests - remove unnecessary describe around 2FA token methods. * PM-5263 - TokenSvc.clearAccessTokenByUserId renamed to just clearAccessToken * PM-5263 - TokenSvc - refactor clearTokens logic and implement individual clear logic which doesn't require vault timeout setting information. * PM-5263 - TokenSvc - Replace all places we have vaultTimeout: number with vaultTimeout: number | null to be accurate. * PM-5263 - TokenSvc.clearTokens - add check for user id; throw if not found * PM-5263 - TokenService - test clearTokens * PM-5263 - TokenSvc Tests - setRefreshToken tested * PM-5263 - TokenSvc tests - getRefreshToken tested + added a new getAccessToken test * PM-5263 - TokenSvc - ClearRefreshToken scenarios tested. * PM-5263 - TokenSvc.clearRefreshToken tests - fix copy pasta * PM-5263 - TokenSvc tests - (1) Fix mistakes in refresh token testing (2) Test setClientId for all scenarios * PM-5263 - TokenSvc tests - (1) Add some getClientId tests (2) clarify lack of awaits * PM-5263 - TokenSvc Tests - WIP - getClientId && clearClientId * PM-5263 - TokenService - getClientSecret - fix error message * PM-5263 - TokenService tests - test all client secret methods * PM-5263 - Update TokenSvc migration to 30th migration * PM-5263 - TokenService - update all tests to initialize data to undefined now that fake state provider supports faking data based on specific key definitions. * PM-5263 - (1) TokenSvc.decodeAccessToken - update static method's error handling (2) TokenSvc tests - test all decodeAccessToken scenarios * PM-5263 - TokenSvc - (1) Add DecodedAccessToken type (2) Refactor getTokenExpirationDate logic to use new type and make proper type checks for numbers for exp claim values. * PM-5263 - TokenSvc tests - test getTokenExpirationDate method. * PM-5263 - TokenSvc - (1) Update DecodedAccessToken docs (2) Tweak naming in tokenSecondsRemaining * PM-5263 - TokenSvc abstraction - add jsdoc for tokenSecondsRemaining * PM-5263 - TokenSvc tests - test tokenSecondsRemaining * PM-5263 - TokenSvc - DecodedAccessToken type - update sstamp info * PM-5263 - TokenService - fix flaky tokenSecondsRemaining tests by locking time * PM-5263 - TokenSvc Tests - Test tokenNeedsRefresh * PM-5263 - (1) TokenSvc - Refactor getUserId to add extra safety (2) TokenSvc tests - test getUserId * PM-5263 - (1) TokenSvc - refactor getUserIdFromAccessToken to handle decoding errors (2) TokenSvc tests - test getUserIdFromAccessToken * PM-5263 - (1) TokenSvc - Refactor getEmail to handle decoding errors + check for specific, expected type (2) TokenSvc tests - test getEmail * PM-5263 - TokenSvc tests - clean up comment * PM-5263 - (1) TokenSvc - getEmailVerified - refactor (2) TokenSvc tests - add getEmailVerified tests * PM-5263 - (1) TokenSvc - refactor getName (2) TokenSvc tests - test getName * PM-5263 - (1) TokenSvc - refactor getIssuer (2) TokenSvc tests - test getIssuer * PM-5263 - TokenSvc - remove unnecessary "as type" statements now that we have a decoded access token type * PM-5263 - (1) TokenSvc - refactor getIsExternal (2) TokenSvc Tests - test getIsExternal * PM-5263 - TokenSvc abstraction - tune up rest of docs. * PM-5263 - TokenSvc - clean up promise<any> and replace with promise<void> * PM-5263 - TokenSvc abstraction - more docs. * PM-5263 - Clean up TODO as I've tested every method in token svc. * PM-5263 - (1) Extract JWT decode logic into auth owned utility function out of the token service (2) Update TokenService decode logic to use new utility function (3) Update LastPassDirectImportService + vault.ts to use new utility function and remove token service dependency. (4) Update tests + migrate tests to new utility test file. * PM-5263 - Rename decodeJwtTokenToJson to decode-jwt-token-to-json to meet lint rules excluding capitals * PM-5263 - TokenSvc + tests - fix all get methods to return undefined like they did before instead of throwing an error if a user id isn't provided. * PM-5263 - Services.module - add missing token service dep * PM-5263 - Update token svc migrations to be 32nd migration * PM-5263 - Popup - Services.module - Remove token service as it no longer requires a background service due to the migration to state provider. The service definition in jslib-services module is enough. * PM-5263 - BaseLoginStrategy - Extract email out of getTwoFactorToken method call for easier debugging. * PM-5263 - Login Comp - Set email into memory on login service so that base login strategy can access user email for looking up 2FA token stored in global state. * PM-5263 - (1) LoginComp - remove loginSvc.setEmail call as no longer necessary + introduced issues w/ popup and background in browser extension (2) AuthReq & Password login strategies now just pass in email to buildTwoFactor method. * PM-5263 - SsoLoginSvc + abstraction - Add key definition and get/set methods for saving user email in session storage so it persists across the SSO redirect. * PM-5263 - Base Login Strategy - BuildTwoFactor - only try to get 2FA token if we have an email to look up their token * PM-5263 - Remove LoginService dependency from LoginStrategyService * PM-5263 - (1) Save off user email when they click enterprise SSO on all clients in login comp (2) Retrieve it and pass it into login strategy in SSO comp * PM-5263 - (1) TokenSvc - update 2FA token methods to be more safe in case user removes record from local storage (2) Add test cases + missing clearTwoFactorToken tests * PM-5263 - Browser SSO login - save user email for browser SSO process * PM-5263 - Finish removing login service from login strategy tests. * PM-5263 - More removals of the login service from the login strategy tests. * PM-5263 - Main.ts - platformUtilsSvc no longer used in TokenSvc so remove it from desktop main.ts * PM-5263 - Fix failing login strategy service tests * PM-5263 - Bump token svc migration values to migration 35 after merging in main * PM-5263 - Bump token svc migration version * PM-5263 - TokenService.clearTwoFactorToken - use delete instead of setting values to null per discussion with Justin Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc + decode JWT token tests - anonymize my information Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - update clear token tests based on actual deletion * PM-5263 - Add docs per PR feedback * PM-5263 - (1) Move ownership of clearing two factor token on rejection from server to base login strategy (2) Each login strategy that supports remember 2FA logic now persists user entered email in its data (3) Base login strategy processTwoFactorResponse now clears 2FA token (4) Updated base login strategy tests to affirm the clearing of the 2FA token * Update libs/auth/src/common/login-strategies/login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * PM-5263 - Login Strategy - per PR feedback, add jsdoc comments to each method I've touched for this PR. * PM-5263 - (1) TokenSvc - adjust setTokens, setAccessToken, setRefreshToken, and clearRefreshToken based on PR feedback to remove optional user ids where possible and improve public interface (2) TokenSvc Abstraction - update docs and abstractions based on removed user ids and changed logic (3) TokenSvc tests - update tests to add new test cases, remove no longer relevant ones, and update test names. * PM-5263 - Bump migrations again --------- Co-authored-by: Matt Gibson <git@mgibson.dev> Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com>
2024-03-15 16:50:04 +01:00
import {
ELECTRON_SUPPORTS_SECURE_STORAGE,
ElectronPlatformUtilsService,
} from "../../platform/services/electron-platform-utils.service";
import { ElectronRendererMessageSender } from "../../platform/services/electron-renderer-message.sender";
import { ElectronRendererSecureStorageService } from "../../platform/services/electron-renderer-secure-storage.service";
import { ElectronRendererStorageService } from "../../platform/services/electron-renderer-storage.service";
import { ElectronStateService } from "../../platform/services/electron-state.service";
import { I18nRendererService } from "../../platform/services/i18n.renderer.service";
import { fromIpcMessaging } from "../../platform/utils/from-ipc-messaging";
import { fromIpcSystemTheme } from "../../platform/utils/from-ipc-system-theme";
import { EncryptedMessageHandlerService } from "../../services/encrypted-message-handler.service";
import { NativeMessageHandlerService } from "../../services/native-message-handler.service";
import { NativeMessagingService } from "../../services/native-messaging.service";
import { SearchBarService } from "../layout/search/search-bar.service";
import { DesktopFileDownloadService } from "./desktop-file-download.service";
import { InitService } from "./init.service";
import { NativeMessagingManifestService } from "./native-messaging-manifest.service";
import { RendererCryptoFunctionService } from "./renderer-crypto-function.service";
const RELOAD_CALLBACK = new SafeInjectionToken<() => any>("RELOAD_CALLBACK");
// Desktop has its own Account definition which must be used in its StateService
const DESKTOP_STATE_FACTORY = new SafeInjectionToken<StateFactory<GlobalState, Account>>(
"DESKTOP_STATE_FACTORY",
);
/**
* Provider definitions used in the ngModule.
* Add your provider definition here using the safeProvider function as a wrapper. This will give you type safety.
* If you need help please ask for it, do NOT change the type of this array.
*/
const safeProviders: SafeProvider[] = [
safeProvider(InitService),
safeProvider(NativeMessagingService),
safeProvider(SearchBarService),
safeProvider(LoginGuard),
safeProvider(DialogService),
safeProvider({
provide: APP_INITIALIZER as SafeInjectionToken<() => void>,
useFactory: (initService: InitService) => initService.init(),
deps: [InitService],
multi: true,
}),
safeProvider({
provide: DESKTOP_STATE_FACTORY,
useValue: new StateFactory(GlobalState, Account),
}),
safeProvider({
provide: STATE_FACTORY,
useValue: null,
}),
safeProvider({
provide: RELOAD_CALLBACK,
useValue: null,
}),
safeProvider({
provide: LogServiceAbstraction,
useClass: ElectronLogRendererService,
deps: [],
}),
safeProvider({
provide: PlatformUtilsServiceAbstraction,
useClass: ElectronPlatformUtilsService,
deps: [I18nServiceAbstraction, MessagingServiceAbstraction],
}),
safeProvider({
// We manually override the value of SUPPORTS_SECURE_STORAGE here to avoid
// the TokenService having to inject the PlatformUtilsService which introduces a
// circular dependency on Desktop only.
provide: SUPPORTS_SECURE_STORAGE,
useValue: ELECTRON_SUPPORTS_SECURE_STORAGE,
}),
safeProvider({
provide: I18nServiceAbstraction,
useClass: I18nRendererService,
deps: [SYSTEM_LANGUAGE, LOCALES_DIRECTORY, GlobalStateProvider],
}),
safeProvider({
provide: MessageSender,
useFactory: (subject: Subject<Message<object>>) =>
MessageSender.combine(
new ElectronRendererMessageSender(), // Communication with main process
new SubjectMessageSender(subject), // Communication with ourself
),
deps: [INTRAPROCESS_MESSAGING_SUBJECT],
}),
safeProvider({
provide: MessageListener,
useFactory: (subject: Subject<Message<object>>) =>
new MessageListener(
merge(
subject.asObservable(), // For messages from the same context
fromIpcMessaging(), // For messages from the main process
),
),
deps: [INTRAPROCESS_MESSAGING_SUBJECT],
}),
safeProvider({
provide: AbstractStorageService,
useClass: ElectronRendererStorageService,
deps: [],
}),
safeProvider({
provide: SECURE_STORAGE,
useClass: ElectronRendererSecureStorageService,
deps: [],
}),
safeProvider({ provide: MEMORY_STORAGE, useClass: MemoryStorageService, deps: [] }),
safeProvider({
provide: OBSERVABLE_MEMORY_STORAGE,
useClass: MemoryStorageServiceForStateProviders,
deps: [],
}),
safeProvider({ provide: OBSERVABLE_DISK_STORAGE, useExisting: AbstractStorageService }),
safeProvider({
provide: SystemServiceAbstraction,
useClass: SystemService,
deps: [
2024-04-19 22:50:07 +02:00
AccountServiceAbstraction,
2024-04-05 21:38:10 +02:00
PinServiceAbstraction,
MessagingServiceAbstraction,
PlatformUtilsServiceAbstraction,
RELOAD_CALLBACK,
StateServiceAbstraction,
AutofillSettingsServiceAbstraction,
VaultTimeoutSettingsService,
BiometricStateService,
],
}),
safeProvider({
provide: StateServiceAbstraction,
useClass: ElectronStateService,
deps: [
AbstractStorageService,
SECURE_STORAGE,
MEMORY_STORAGE,
LogService,
DESKTOP_STATE_FACTORY,
AccountServiceAbstraction,
EnvironmentService,
TokenService,
MigrationRunner,
],
}),
safeProvider({
provide: FileDownloadService,
useClass: DesktopFileDownloadService,
deps: [],
}),
safeProvider({
provide: SYSTEM_THEME_OBSERVABLE,
useFactory: () => fromIpcSystemTheme(),
deps: [],
}),
safeProvider({
provide: EncryptedMessageHandlerService,
deps: [
StateServiceAbstraction,
AuthServiceAbstraction,
CipherServiceAbstraction,
PolicyServiceAbstraction,
MessagingServiceAbstraction,
PasswordGenerationServiceAbstraction,
],
}),
safeProvider({
provide: NativeMessageHandlerService,
deps: [
StateServiceAbstraction,
CryptoServiceAbstraction,
CryptoFunctionServiceAbstraction,
MessagingServiceAbstraction,
EncryptedMessageHandlerService,
DialogService,
DesktopAutofillSettingsService,
],
}),
safeProvider({
provide: CryptoFunctionServiceAbstraction,
useClass: RendererCryptoFunctionService,
deps: [WINDOW],
}),
safeProvider({
provide: CryptoServiceAbstraction,
useClass: ElectronCryptoService,
deps: [
2024-04-11 00:37:03 +02:00
PinServiceAbstraction,
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
InternalMasterPasswordServiceAbstraction,
KeyGenerationServiceAbstraction,
CryptoFunctionServiceAbstraction,
EncryptService,
PlatformUtilsServiceAbstraction,
LogService,
StateServiceAbstraction,
AccountServiceAbstraction,
StateProvider,
BiometricStateService,
KdfConfigServiceAbstraction,
],
}),
safeProvider({
provide: DesktopSettingsService,
deps: [StateProvider],
}),
safeProvider({
provide: DesktopAutofillSettingsService,
deps: [StateProvider],
}),
safeProvider({
provide: NativeMessagingManifestService,
useClass: NativeMessagingManifestService,
deps: [],
}),
];
@NgModule({
imports: [JslibServicesModule],
declarations: [],
// Do not register your dependency here! Add it to the typesafeProviders array using the helper function
providers: safeProviders,
})
export class ServicesModule {}