1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-22 11:45:59 +01:00

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>
This commit is contained in:
Jared Snider 2024-03-15 11:50:04 -04:00 committed by GitHub
parent c5a56397d8
commit 161fb1da5d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
57 changed files with 4242 additions and 437 deletions

View File

@ -7,13 +7,29 @@ import {
factory,
} from "../../../platform/background/service-factories/factory-options";
import {
stateServiceFactory,
StateServiceInitOptions,
} from "../../../platform/background/service-factories/state-service.factory";
GlobalStateProviderInitOptions,
globalStateProviderFactory,
} from "../../../platform/background/service-factories/global-state-provider.factory";
import {
PlatformUtilsServiceInitOptions,
platformUtilsServiceFactory,
} from "../../../platform/background/service-factories/platform-utils-service.factory";
import {
SingleUserStateProviderInitOptions,
singleUserStateProviderFactory,
} from "../../../platform/background/service-factories/single-user-state-provider.factory";
import {
SecureStorageServiceInitOptions,
secureStorageServiceFactory,
} from "../../../platform/background/service-factories/storage-service.factory";
type TokenServiceFactoryOptions = FactoryOptions;
export type TokenServiceInitOptions = TokenServiceFactoryOptions & StateServiceInitOptions;
export type TokenServiceInitOptions = TokenServiceFactoryOptions &
SingleUserStateProviderInitOptions &
GlobalStateProviderInitOptions &
PlatformUtilsServiceInitOptions &
SecureStorageServiceInitOptions;
export function tokenServiceFactory(
cache: { tokenService?: AbstractTokenService } & CachedServices,
@ -23,6 +39,12 @@ export function tokenServiceFactory(
cache,
"tokenService",
opts,
async () => new TokenService(await stateServiceFactory(cache, opts)),
async () =>
new TokenService(
await singleUserStateProviderFactory(cache, opts),
await globalStateProviderFactory(cache, opts),
(await platformUtilsServiceFactory(cache, opts)).supportsSecureStorage(),
await secureStorageServiceFactory(cache, opts),
),
);
}

View File

@ -91,6 +91,8 @@ export class LoginComponent extends BaseLoginComponent {
}
async launchSsoBrowser() {
// Save off email for SSO
await this.ssoLoginService.setSsoEmail(this.formGroup.value.email);
await this.loginService.saveEmailSettings();
// Generate necessary sso params
const passwordOptions: any = {

View File

@ -184,6 +184,11 @@ export class MainContextMenuHandler {
stateServiceOptions: {
stateFactory: stateFactory,
},
platformUtilsServiceOptions: {
clipboardWriteCallback: () => Promise.resolve(),
biometricCallback: () => Promise.resolve(false),
win: self,
},
};
return new MainContextMenuHandler(

View File

@ -427,6 +427,21 @@ export default class MainBackground {
);
this.biometricStateService = new DefaultBiometricStateService(this.stateProvider);
this.userNotificationSettingsService = new UserNotificationSettingsService(this.stateProvider);
this.platformUtilsService = new BackgroundPlatformUtilsService(
this.messagingService,
(clipboardValue, clearMs) => this.clearClipboard(clipboardValue, clearMs),
async () => this.biometricUnlock(),
self,
);
this.tokenService = new TokenService(
this.singleUserStateProvider,
this.globalStateProvider,
this.platformUtilsService.supportsSecureStorage(),
this.secureStorageService,
);
const migrationRunner = new MigrationRunner(
this.storageService,
this.logService,
@ -441,15 +456,9 @@ export default class MainBackground {
new StateFactory(GlobalState, Account),
this.accountService,
this.environmentService,
this.tokenService,
migrationRunner,
);
this.userNotificationSettingsService = new UserNotificationSettingsService(this.stateProvider);
this.platformUtilsService = new BackgroundPlatformUtilsService(
this.messagingService,
(clipboardValue, clearMs) => this.clearClipboard(clipboardValue, clearMs),
async () => this.biometricUnlock(),
self,
);
const themeStateService = new DefaultThemeStateService(this.globalStateProvider);
@ -465,13 +474,14 @@ export default class MainBackground {
this.stateProvider,
this.biometricStateService,
);
this.tokenService = new TokenService(this.stateService);
this.appIdService = new AppIdService(this.globalStateProvider);
this.apiService = new ApiService(
this.tokenService,
this.platformUtilsService,
this.environmentService,
this.appIdService,
this.stateService,
(expired: boolean) => this.logout(expired),
);
this.domainSettingsService = new DefaultDomainSettingsService(this.stateProvider);

View File

@ -20,6 +20,7 @@ import {
PlatformUtilsServiceInitOptions,
platformUtilsServiceFactory,
} from "./platform-utils-service.factory";
import { stateServiceFactory, StateServiceInitOptions } from "./state-service.factory";
type ApiServiceFactoryOptions = FactoryOptions & {
apiServiceOptions: {
@ -32,7 +33,8 @@ export type ApiServiceInitOptions = ApiServiceFactoryOptions &
TokenServiceInitOptions &
PlatformUtilsServiceInitOptions &
EnvironmentServiceInitOptions &
AppIdServiceInitOptions;
AppIdServiceInitOptions &
StateServiceInitOptions;
export function apiServiceFactory(
cache: { apiService?: AbstractApiService } & CachedServices,
@ -48,6 +50,7 @@ export function apiServiceFactory(
await platformUtilsServiceFactory(cache, opts),
await environmentServiceFactory(cache, opts),
await appIdServiceFactory(cache, opts),
await stateServiceFactory(cache, opts),
opts.apiServiceOptions.logoutCallback,
opts.apiServiceOptions.customUserAgent,
),

View File

@ -5,6 +5,10 @@ import {
accountServiceFactory,
AccountServiceInitOptions,
} from "../../../auth/background/service-factories/account-service.factory";
import {
tokenServiceFactory,
TokenServiceInitOptions,
} from "../../../auth/background/service-factories/token-service.factory";
import { Account } from "../../../models/account";
import { BrowserStateService } from "../../services/browser-state.service";
@ -38,6 +42,7 @@ export type StateServiceInitOptions = StateServiceFactoryOptions &
LogServiceInitOptions &
AccountServiceInitOptions &
EnvironmentServiceInitOptions &
TokenServiceInitOptions &
MigrationRunnerInitOptions;
export async function stateServiceFactory(
@ -57,6 +62,7 @@ export async function stateServiceFactory(
opts.stateServiceOptions.stateFactory,
await accountServiceFactory(cache, opts),
await environmentServiceFactory(cache, opts),
await tokenServiceFactory(cache, opts),
await migrationRunnerFactory(cache, opts),
opts.stateServiceOptions.useAccountCache,
),

View File

@ -1,5 +1,6 @@
import { mock, MockProxy } from "jest-mock-extended";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import {
@ -32,6 +33,7 @@ describe("Browser State Service", () => {
let stateFactory: MockProxy<StateFactory<GlobalState, Account>>;
let useAccountCache: boolean;
let environmentService: MockProxy<EnvironmentService>;
let tokenService: MockProxy<TokenService>;
let migrationRunner: MockProxy<MigrationRunner>;
let state: State<GlobalState, Account>;
@ -46,6 +48,7 @@ describe("Browser State Service", () => {
logService = mock();
stateFactory = mock();
environmentService = mock();
tokenService = mock();
migrationRunner = mock();
// turn off account cache for tests
useAccountCache = false;
@ -77,6 +80,7 @@ describe("Browser State Service", () => {
stateFactory,
accountService,
environmentService,
tokenService,
migrationRunner,
useAccountCache,
);

View File

@ -1,6 +1,7 @@
import { BehaviorSubject } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import {
@ -45,6 +46,7 @@ export class BrowserStateService
stateFactory: StateFactory<GlobalState, Account>,
accountService: AccountService,
environmentService: EnvironmentService,
tokenService: TokenService,
migrationRunner: MigrationRunner,
useAccountCache = true,
) {
@ -56,6 +58,7 @@ export class BrowserStateService
stateFactory,
accountService,
environmentService,
tokenService,
migrationRunner,
useAccountCache,
);

View File

@ -233,7 +233,6 @@ function getBgService<T>(service: keyof MainBackground) {
deps: [],
},
{ provide: TotpService, useFactory: getBgService<TotpService>("totpService"), deps: [] },
{ provide: TokenService, useFactory: getBgService<TokenService>("tokenService"), deps: [] },
{
provide: I18nServiceAbstraction,
useFactory: (globalStateProvider: GlobalStateProvider) => {
@ -445,6 +444,7 @@ function getBgService<T>(service: keyof MainBackground) {
logService: LogServiceAbstraction,
accountService: AccountServiceAbstraction,
environmentService: EnvironmentService,
tokenService: TokenService,
migrationRunner: MigrationRunner,
) => {
return new BrowserStateService(
@ -455,6 +455,7 @@ function getBgService<T>(service: keyof MainBackground) {
new StateFactory(GlobalState, Account),
accountService,
environmentService,
tokenService,
migrationRunner,
);
},
@ -465,6 +466,7 @@ function getBgService<T>(service: keyof MainBackground) {
LogServiceAbstraction,
AccountServiceAbstraction,
EnvironmentService,
TokenService,
MigrationRunner,
],
},

View File

@ -203,6 +203,7 @@ export class LoginCommand {
ssoCodeVerifier,
this.ssoRedirectUri,
orgIdentifier,
undefined, // email to look up 2FA token not required as CLI can't remember 2FA token
twoFactor,
),
);

View File

@ -310,6 +310,13 @@ export class Main {
this.environmentService = new EnvironmentService(this.stateProvider, this.accountService);
this.tokenService = new TokenService(
this.singleUserStateProvider,
this.globalStateProvider,
this.platformUtilsService.supportsSecureStorage(),
this.secureStorageService,
);
const migrationRunner = new MigrationRunner(
this.storageService,
this.logService,
@ -324,6 +331,7 @@ export class Main {
new StateFactory(GlobalState, Account),
this.accountService,
this.environmentService,
this.tokenService,
migrationRunner,
);
@ -341,7 +349,6 @@ export class Main {
);
this.appIdService = new AppIdService(this.globalStateProvider);
this.tokenService = new TokenService(this.stateService);
const customUserAgent =
"Bitwarden_CLI/" +
@ -354,6 +361,7 @@ export class Main {
this.platformUtilsService,
this.environmentService,
this.appIdService,
this.stateService,
async (expired: boolean) => await this.logout(),
customUserAgent,
);

View File

@ -6,6 +6,7 @@ import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { ApiService } from "@bitwarden/common/services/api.service";
(global as any).fetch = fe.default;
@ -20,6 +21,7 @@ export class NodeApiService extends ApiService {
platformUtilsService: PlatformUtilsService,
environmentService: EnvironmentService,
appIdService: AppIdService,
stateService: StateService,
logoutCallback: (expired: boolean) => Promise<void>,
customUserAgent: string = null,
) {
@ -28,6 +30,7 @@ export class NodeApiService extends ApiService {
platformUtilsService,
environmentService,
appIdService,
stateService,
logoutCallback,
customUserAgent,
);

View File

@ -10,6 +10,7 @@ import {
OBSERVABLE_MEMORY_STORAGE,
OBSERVABLE_DISK_STORAGE,
WINDOW,
SUPPORTS_SECURE_STORAGE,
SYSTEM_THEME_OBSERVABLE,
} from "@bitwarden/angular/services/injection-tokens";
import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module";
@ -18,6 +19,7 @@ import { PolicyService as PolicyServiceAbstraction } from "@bitwarden/common/adm
import { AccountService as AccountServiceAbstraction } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService as AuthServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth.service";
import { LoginService as LoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/login.service";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { LoginService } from "@bitwarden/common/auth/services/login.service";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { BroadcasterService as BroadcasterServiceAbstraction } from "@bitwarden/common/platform/abstractions/broadcaster.service";
@ -54,7 +56,10 @@ import { LoginGuard } from "../../auth/guards/login.guard";
import { Account } from "../../models/account";
import { ElectronCryptoService } from "../../platform/services/electron-crypto.service";
import { ElectronLogRendererService } from "../../platform/services/electron-log.renderer.service";
import { ElectronPlatformUtilsService } from "../../platform/services/electron-platform-utils.service";
import {
ELECTRON_SUPPORTS_SECURE_STORAGE,
ElectronPlatformUtilsService,
} from "../../platform/services/electron-platform-utils.service";
import { ElectronRendererMessagingService } from "../../platform/services/electron-renderer-messaging.service";
import { ElectronRendererSecureStorageService } from "../../platform/services/electron-renderer-secure-storage.service";
import { ElectronRendererStorageService } from "../../platform/services/electron-renderer-storage.service";
@ -101,6 +106,13 @@ const RELOAD_CALLBACK = new InjectionToken<() => any>("RELOAD_CALLBACK");
useClass: ElectronPlatformUtilsService,
deps: [I18nServiceAbstraction, MessagingServiceAbstraction],
},
{
// 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,
},
{
provide: I18nServiceAbstraction,
useClass: I18nRendererService,
@ -140,6 +152,7 @@ const RELOAD_CALLBACK = new InjectionToken<() => any>("RELOAD_CALLBACK");
STATE_FACTORY,
AccountServiceAbstraction,
EnvironmentService,
TokenService,
MigrationRunner,
STATE_SERVICE_USE_CACHE,
],

View File

@ -2,7 +2,9 @@ import * as path from "path";
import { app } from "electron";
import { TokenService as TokenServiceAbstraction } from "@bitwarden/common/auth/abstractions/token.service";
import { AccountServiceImplementation } from "@bitwarden/common/auth/services/account.service";
import { TokenService } from "@bitwarden/common/auth/services/token.service";
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { DefaultBiometricStateService } from "@bitwarden/common/platform/biometrics/biometric-state.service";
import { StateFactory } from "@bitwarden/common/platform/factories/state-factory";
@ -36,6 +38,7 @@ import { ClipboardMain } from "./platform/main/clipboard.main";
import { DesktopCredentialStorageListener } from "./platform/main/desktop-credential-storage-listener";
import { MainCryptoFunctionService } from "./platform/main/main-crypto-function.service";
import { ElectronLogMainService } from "./platform/services/electron-log.main.service";
import { ELECTRON_SUPPORTS_SECURE_STORAGE } from "./platform/services/electron-platform-utils.service";
import { ElectronStateService } from "./platform/services/electron-state.service";
import { ElectronStorageService } from "./platform/services/electron-storage.service";
import { I18nMainService } from "./platform/services/i18n.main.service";
@ -53,6 +56,7 @@ export class Main {
mainCryptoFunctionService: MainCryptoFunctionService;
desktopCredentialStorageListener: DesktopCredentialStorageListener;
migrationRunner: MigrationRunner;
tokenService: TokenServiceAbstraction;
windowMain: WindowMain;
messagingMain: MessagingMain;
@ -129,8 +133,13 @@ export class Main {
stateEventRegistrarService,
);
const activeUserStateProvider = new DefaultActiveUserStateProvider(
accountService,
singleUserStateProvider,
);
const stateProvider = new DefaultStateProvider(
new DefaultActiveUserStateProvider(accountService, singleUserStateProvider),
activeUserStateProvider,
singleUserStateProvider,
globalStateProvider,
new DefaultDerivedStateProvider(this.memoryStorageForStateProviders),
@ -138,6 +147,13 @@ export class Main {
this.environmentService = new EnvironmentService(stateProvider, accountService);
this.tokenService = new TokenService(
singleUserStateProvider,
globalStateProvider,
ELECTRON_SUPPORTS_SECURE_STORAGE,
this.storageService,
);
this.migrationRunner = new MigrationRunner(
this.storageService,
this.logService,
@ -155,6 +171,7 @@ export class Main {
new StateFactory(GlobalState, Account),
accountService, // will not broadcast logouts. This is a hack until we can remove messaging dependency
this.environmentService,
this.tokenService,
this.migrationRunner,
false, // Do not use disk caching because this will get out of sync with the renderer service
);
@ -176,6 +193,7 @@ export class Main {
this.messagingService = new ElectronMainMessagingService(this.windowMain, (message) => {
this.messagingMain.onMessage(message);
});
this.powerMonitorMain = new PowerMonitorMain(this.messagingService);
this.menuMain = new MenuMain(
this.i18nService,

View File

@ -8,6 +8,8 @@ import {
import { ClipboardWriteMessage } from "../types/clipboard";
export const ELECTRON_SUPPORTS_SECURE_STORAGE = true;
export class ElectronPlatformUtilsService implements PlatformUtilsService {
constructor(
protected i18nService: I18nService,
@ -142,7 +144,7 @@ export class ElectronPlatformUtilsService implements PlatformUtilsService {
}
supportsSecureStorage(): boolean {
return true;
return ELECTRON_SUPPORTS_SECURE_STORAGE;
}
getAutofillKeyboardShortcut(): Promise<string> {

View File

@ -7,6 +7,7 @@ import {
STATE_SERVICE_USE_CACHE,
} from "@bitwarden/angular/services/injection-tokens";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import {
@ -33,6 +34,7 @@ export class StateService extends BaseStateService<GlobalState, Account> {
@Inject(STATE_FACTORY) stateFactory: StateFactory<GlobalState, Account>,
accountService: AccountService,
environmentService: EnvironmentService,
tokenService: TokenService,
migrationRunner: MigrationRunner,
@Inject(STATE_SERVICE_USE_CACHE) useAccountCache = true,
) {
@ -44,6 +46,7 @@ export class StateService extends BaseStateService<GlobalState, Account> {
stateFactory,
accountService,
environmentService,
tokenService,
migrationRunner,
useAccountCache,
);

View File

@ -149,6 +149,7 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit,
this.captchaToken,
null,
);
this.formPromise = this.loginStrategyService.logIn(credentials);
const response = await this.formPromise;
this.setFormValues();
@ -302,6 +303,9 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit,
async saveEmailSettings() {
this.setFormValues();
await this.loginService.saveEmailSettings();
// Save off email for SSO
await this.ssoLoginService.setSsoEmail(this.formGroup.value.email);
}
// Legacy accounts used the master key to encrypt data. Migration is required

View File

@ -182,11 +182,14 @@ export class SsoComponent {
private async logIn(code: string, codeVerifier: string, orgSsoIdentifier: string): Promise<void> {
this.loggingIn = true;
try {
const email = await this.ssoLoginService.getSsoEmail();
const credentials = new SsoLoginCredentials(
code,
codeVerifier,
this.redirectUri,
orgSsoIdentifier,
email,
);
this.formPromise = this.loginStrategyService.logIn(credentials);
const authResult = await this.formPromise;

View File

@ -42,6 +42,7 @@ export const LOGOUT_CALLBACK = new SafeInjectionToken<
export const LOCKED_CALLBACK = new SafeInjectionToken<(userId?: string) => Promise<void>>(
"LOCKED_CALLBACK",
);
export const SUPPORTS_SECURE_STORAGE = new SafeInjectionToken<boolean>("SUPPORTS_SECURE_STORAGE");
export const LOCALES_DIRECTORY = new SafeInjectionToken<string>("LOCALES_DIRECTORY");
export const SYSTEM_LANGUAGE = new SafeInjectionToken<string>("SYSTEM_LANGUAGE");
export const LOG_MAC_FAILURES = new SafeInjectionToken<boolean>("LOG_MAC_FAILURES");

View File

@ -250,6 +250,7 @@ import {
SECURE_STORAGE,
STATE_FACTORY,
STATE_SERVICE_USE_CACHE,
SUPPORTS_SECURE_STORAGE,
SYSTEM_LANGUAGE,
SYSTEM_THEME_OBSERVABLE,
WINDOW,
@ -272,6 +273,12 @@ const typesafeProviders: Array<SafeProvider> = [
useFactory: (i18nService: I18nServiceAbstraction) => i18nService.translationLocale,
deps: [I18nServiceAbstraction],
}),
safeProvider({
provide: SUPPORTS_SECURE_STORAGE,
useFactory: (platformUtilsService: PlatformUtilsServiceAbstraction) =>
platformUtilsService.supportsSecureStorage(),
deps: [PlatformUtilsServiceAbstraction],
}),
safeProvider({
provide: LOCALES_DIRECTORY,
useValue: "./locales",
@ -475,7 +482,12 @@ const typesafeProviders: Array<SafeProvider> = [
safeProvider({
provide: TokenServiceAbstraction,
useClass: TokenService,
deps: [StateServiceAbstraction],
deps: [
SingleUserStateProvider,
GlobalStateProvider,
SUPPORTS_SECURE_STORAGE,
AbstractStorageService,
],
}),
safeProvider({
provide: KeyGenerationServiceAbstraction,
@ -519,6 +531,7 @@ const typesafeProviders: Array<SafeProvider> = [
PlatformUtilsServiceAbstraction,
EnvironmentServiceAbstraction,
AppIdServiceAbstraction,
StateServiceAbstraction,
LOGOUT_CALLBACK,
],
}),
@ -621,6 +634,7 @@ const typesafeProviders: Array<SafeProvider> = [
STATE_FACTORY,
AccountServiceAbstraction,
EnvironmentServiceAbstraction,
TokenServiceAbstraction,
MigrationRunner,
STATE_SERVICE_USE_CACHE,
],

View File

@ -4,3 +4,4 @@
export * from "./abstractions";
export * from "./models";
export * from "./services";
export * from "./utilities";

View File

@ -67,7 +67,7 @@ describe("AuthRequestLoginStrategy", () => {
tokenService.getTwoFactorToken.mockResolvedValue(null);
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.decodeToken.mockResolvedValue({});
tokenService.decodeAccessToken.mockResolvedValue({});
authRequestLoginStrategy = new AuthRequestLoginStrategy(
cache,

View File

@ -79,7 +79,7 @@ export class AuthRequestLoginStrategy extends LoginStrategy {
credentials.email,
credentials.accessCode,
null,
await this.buildTwoFactor(credentials.twoFactor),
await this.buildTwoFactor(credentials.twoFactor, credentials.email),
await this.buildDeviceRequest(),
);
data.tokenRequest.setAuthRequestAccessCode(credentials.authRequestId);

View File

@ -14,6 +14,7 @@ import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/id
import { IdentityTwoFactorResponse } from "@bitwarden/common/auth/models/response/identity-two-factor.response";
import { MasterPasswordPolicyResponse } from "@bitwarden/common/auth/models/response/master-password-policy.response";
import { IUserDecryptionOptionsServerResponse } from "@bitwarden/common/auth/models/response/user-decryption-options/user-decryption-options.response";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
@ -123,11 +124,12 @@ describe("LoginStrategy", () => {
logService = mock<LogService>();
stateService = mock<StateService>();
twoFactorService = mock<TwoFactorService>();
policyService = mock<PolicyService>();
passwordStrengthService = mock<PasswordStrengthService>();
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.decodeToken.calledWith(accessToken).mockResolvedValue(decodedToken);
tokenService.decodeAccessToken.calledWith(accessToken).mockResolvedValue(decodedToken);
// The base class is abstract so we test it via PasswordLoginStrategy
passwordLoginStrategy = new PasswordLoginStrategy(
@ -167,8 +169,21 @@ describe("LoginStrategy", () => {
const idTokenResponse = identityTokenResponseFactory();
apiService.postIdentityToken.mockResolvedValue(idTokenResponse);
const mockVaultTimeoutAction = VaultTimeoutAction.Lock;
const mockVaultTimeout = 1000;
stateService.getVaultTimeoutAction.mockResolvedValue(mockVaultTimeoutAction);
stateService.getVaultTimeout.mockResolvedValue(mockVaultTimeout);
await passwordLoginStrategy.logIn(credentials);
expect(tokenService.setTokens).toHaveBeenCalledWith(
accessToken,
refreshToken,
mockVaultTimeoutAction,
mockVaultTimeout,
);
expect(stateService.addAccount).toHaveBeenCalledWith(
new Account({
profile: {
@ -184,10 +199,6 @@ describe("LoginStrategy", () => {
},
tokens: {
...new AccountTokens(),
...{
accessToken: accessToken,
refreshToken: refreshToken,
},
},
keys: new AccountKeys(),
decryptionOptions: AccountDecryptionOptions.fromResponse(idTokenResponse),
@ -299,6 +310,7 @@ describe("LoginStrategy", () => {
expect(stateService.addAccount).not.toHaveBeenCalled();
expect(messagingService.send).not.toHaveBeenCalled();
expect(tokenService.clearTwoFactorToken).toHaveBeenCalled();
const expected = new AuthResult();
expected.twoFactorProviders = new Map<TwoFactorProviderType, { [key: string]: string }>();

View File

@ -16,6 +16,7 @@ import { IdentityCaptchaResponse } from "@bitwarden/common/auth/models/response/
import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/identity-token.response";
import { IdentityTwoFactorResponse } from "@bitwarden/common/auth/models/response/identity-two-factor.response";
import { ClientType } from "@bitwarden/common/enums";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { KeysRequest } from "@bitwarden/common/models/request/keys.request";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
@ -49,6 +50,9 @@ export abstract class LoginStrategyData {
| SsoTokenRequest
| WebAuthnLoginTokenRequest;
captchaBypassToken?: string;
/** User's entered email obtained pre-login. */
abstract userEnteredEmail?: string;
}
export abstract class LoginStrategy {
@ -110,21 +114,47 @@ export abstract class LoginStrategy {
return new DeviceRequest(appId, this.platformUtilsService);
}
protected async buildTwoFactor(userProvidedTwoFactor?: TokenTwoFactorRequest) {
/**
* Builds the TokenTwoFactorRequest to be used within other login strategies token requests
* to the server.
* If the user provided a 2FA token in an already created TokenTwoFactorRequest, it will be used.
* If not, and the user has previously remembered a 2FA token, it will be used.
* If neither of these are true, an empty TokenTwoFactorRequest will be returned.
* @param userProvidedTwoFactor - optional - The 2FA token request provided by the caller
* @param email - optional - ensure that email is provided for any login strategies that support remember 2FA functionality
* @returns a promise which resolves to a TokenTwoFactorRequest to be sent to the server
*/
protected async buildTwoFactor(
userProvidedTwoFactor?: TokenTwoFactorRequest,
email?: string,
): Promise<TokenTwoFactorRequest> {
if (userProvidedTwoFactor != null) {
return userProvidedTwoFactor;
}
const storedTwoFactorToken = await this.tokenService.getTwoFactorToken();
if (email) {
const storedTwoFactorToken = await this.tokenService.getTwoFactorToken(email);
if (storedTwoFactorToken != null) {
return new TokenTwoFactorRequest(TwoFactorProviderType.Remember, storedTwoFactorToken, false);
return new TokenTwoFactorRequest(
TwoFactorProviderType.Remember,
storedTwoFactorToken,
false,
);
}
}
return new TokenTwoFactorRequest();
}
protected async saveAccountInformation(tokenResponse: IdentityTokenResponse) {
const accountInformation = await this.tokenService.decodeToken(tokenResponse.accessToken);
/**
* Initializes the account with information from the IdTokenResponse after successful login.
* It also sets the access token and refresh token in the token service.
*
* @param {IdentityTokenResponse} tokenResponse - The response from the server containing the identity token.
* @returns {Promise<void>} - A promise that resolves when the account information has been successfully saved.
*/
protected async saveAccountInformation(tokenResponse: IdentityTokenResponse): Promise<void> {
const accountInformation = await this.tokenService.decodeAccessToken(tokenResponse.accessToken);
// Must persist existing device key if it exists for trusted device decryption to work
// However, we must provide a user id so that the device key can be retrieved
@ -141,6 +171,18 @@ export abstract class LoginStrategy {
// If you don't persist existing admin auth requests on login, they will get deleted.
const adminAuthRequest = await this.stateService.getAdminAuthRequest({ userId });
const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction();
const vaultTimeout = await this.stateService.getVaultTimeout();
// set access token and refresh token before account initialization so authN status can be accurate
// User id will be derived from the access token.
await this.tokenService.setTokens(
tokenResponse.accessToken,
tokenResponse.refreshToken,
vaultTimeoutAction as VaultTimeoutAction,
vaultTimeout,
);
await this.stateService.addAccount(
new Account({
profile: {
@ -158,10 +200,6 @@ export abstract class LoginStrategy {
},
tokens: {
...new AccountTokens(),
...{
accessToken: tokenResponse.accessToken,
refreshToken: tokenResponse.refreshToken,
},
},
keys: accountKeys,
decryptionOptions: AccountDecryptionOptions.fromResponse(tokenResponse),
@ -193,7 +231,10 @@ export abstract class LoginStrategy {
await this.saveAccountInformation(response);
if (response.twoFactorToken != null) {
await this.tokenService.setTwoFactorToken(response);
// note: we can read email from access token b/c it was saved in saveAccountInformation
const userEmail = await this.tokenService.getEmail();
await this.tokenService.setTwoFactorToken(userEmail, response.twoFactorToken);
}
await this.setMasterKey(response);
@ -226,7 +267,18 @@ export abstract class LoginStrategy {
}
}
/**
* Handles the response from the server when a 2FA is required.
* It clears any existing 2FA token, as it's no longer valid, and sets up the necessary data for the 2FA process.
*
* @param {IdentityTwoFactorResponse} response - The response from the server indicating that 2FA is required.
* @returns {Promise<AuthResult>} - A promise that resolves to an AuthResult object
*/
private async processTwoFactorResponse(response: IdentityTwoFactorResponse): Promise<AuthResult> {
// If we get a 2FA required response, then we should clear the 2FA token
// just in case as it is no longer valid.
await this.clearTwoFactorToken();
const result = new AuthResult();
result.twoFactorProviders = response.twoFactorProviders2;
@ -237,6 +289,16 @@ export abstract class LoginStrategy {
return result;
}
/**
* Clears the 2FA token from the token service using the user's email if it exists
*/
private async clearTwoFactorToken() {
const email = this.cache.value.userEnteredEmail;
if (email) {
await this.tokenService.clearTwoFactorToken(email);
}
}
private async processCaptchaResponse(response: IdentityCaptchaResponse): Promise<AuthResult> {
const result = new AuthResult();
result.captchaSiteKey = response.siteKey;

View File

@ -81,7 +81,7 @@ describe("PasswordLoginStrategy", () => {
passwordStrengthService = mock<PasswordStrengthService>();
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.decodeToken.mockResolvedValue({});
tokenService.decodeAccessToken.mockResolvedValue({});
loginStrategyService.makePreloginKey.mockResolvedValue(masterKey);

View File

@ -32,6 +32,10 @@ import { LoginStrategy, LoginStrategyData } from "./login.strategy";
export class PasswordLoginStrategyData implements LoginStrategyData {
tokenRequest: PasswordTokenRequest;
/** User's entered email obtained pre-login. Always present in MP login. */
userEnteredEmail: string;
captchaBypassToken?: string;
/**
* The local version of the user's master key hash
@ -105,6 +109,7 @@ export class PasswordLoginStrategy extends LoginStrategy {
const data = new PasswordLoginStrategyData();
data.masterKey = await this.loginStrategyService.makePreloginKey(masterPassword, email);
data.userEnteredEmail = email;
// Hash the password early (before authentication) so we don't persist it in memory in plaintext
data.localMasterKeyHash = await this.cryptoService.hashMasterKey(
@ -118,7 +123,7 @@ export class PasswordLoginStrategy extends LoginStrategy {
email,
masterKeyHash,
captchaToken,
await this.buildTwoFactor(twoFactor),
await this.buildTwoFactor(twoFactor, email),
await this.buildDeviceRequest(),
);

View File

@ -71,7 +71,7 @@ describe("SsoLoginStrategy", () => {
tokenService.getTwoFactorToken.mockResolvedValue(null);
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.decodeToken.mockResolvedValue({});
tokenService.decodeAccessToken.mockResolvedValue({});
ssoLoginStrategy = new SsoLoginStrategy(
null,

View File

@ -29,6 +29,10 @@ import { LoginStrategyData, LoginStrategy } from "./login.strategy";
export class SsoLoginStrategyData implements LoginStrategyData {
captchaBypassToken: string;
tokenRequest: SsoTokenRequest;
/**
* User's entered email obtained pre-login. Present in most SSO flows, but not CLI + SSO Flow.
*/
userEnteredEmail?: string;
/**
* User email address. Only available after authentication.
*/
@ -105,11 +109,14 @@ export class SsoLoginStrategy extends LoginStrategy {
async logIn(credentials: SsoLoginCredentials) {
const data = new SsoLoginStrategyData();
data.orgId = credentials.orgId;
data.userEnteredEmail = credentials.email;
data.tokenRequest = new SsoTokenRequest(
credentials.code,
credentials.codeVerifier,
credentials.redirectUrl,
await this.buildTwoFactor(credentials.twoFactor),
await this.buildTwoFactor(credentials.twoFactor, credentials.email),
await this.buildDeviceRequest(),
);

View File

@ -4,6 +4,7 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
@ -59,7 +60,7 @@ describe("UserApiLoginStrategy", () => {
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.getTwoFactorToken.mockResolvedValue(null);
tokenService.decodeToken.mockResolvedValue({});
tokenService.decodeAccessToken.mockResolvedValue({});
apiLogInStrategy = new UserApiLoginStrategy(
cache,
@ -101,10 +102,23 @@ describe("UserApiLoginStrategy", () => {
it("sets the local environment after a successful login", async () => {
apiService.postIdentityToken.mockResolvedValue(identityTokenResponseFactory());
const mockVaultTimeoutAction = VaultTimeoutAction.Lock;
const mockVaultTimeout = 60;
stateService.getVaultTimeoutAction.mockResolvedValue(mockVaultTimeoutAction);
stateService.getVaultTimeout.mockResolvedValue(mockVaultTimeout);
await apiLogInStrategy.logIn(credentials);
expect(stateService.setApiKeyClientId).toHaveBeenCalledWith(apiClientId);
expect(stateService.setApiKeyClientSecret).toHaveBeenCalledWith(apiClientSecret);
expect(tokenService.setClientId).toHaveBeenCalledWith(
apiClientId,
mockVaultTimeoutAction,
mockVaultTimeout,
);
expect(tokenService.setClientSecret).toHaveBeenCalledWith(
apiClientSecret,
mockVaultTimeoutAction,
mockVaultTimeout,
);
expect(stateService.addAccount).toHaveBeenCalled();
});

View File

@ -7,6 +7,7 @@ import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
import { UserApiTokenRequest } from "@bitwarden/common/auth/models/request/identity-token/user-api-token.request";
import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/identity-token.response";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
@ -104,9 +105,21 @@ export class UserApiLoginStrategy extends LoginStrategy {
protected async saveAccountInformation(tokenResponse: IdentityTokenResponse) {
await super.saveAccountInformation(tokenResponse);
const vaultTimeout = await this.stateService.getVaultTimeout();
const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction();
const tokenRequest = this.cache.value.tokenRequest;
await this.stateService.setApiKeyClientId(tokenRequest.clientId);
await this.stateService.setApiKeyClientSecret(tokenRequest.clientSecret);
await this.tokenService.setClientId(
tokenRequest.clientId,
vaultTimeoutAction as VaultTimeoutAction,
vaultTimeout,
);
await this.tokenService.setClientSecret(
tokenRequest.clientSecret,
vaultTimeoutAction as VaultTimeoutAction,
vaultTimeout,
);
}
exportCache(): CacheData {

View File

@ -71,7 +71,7 @@ describe("WebAuthnLoginStrategy", () => {
tokenService.getTwoFactorToken.mockResolvedValue(null);
appIdService.getAppId.mockResolvedValue(deviceId);
tokenService.decodeToken.mockResolvedValue({});
tokenService.decodeAccessToken.mockResolvedValue({});
webAuthnLoginStrategy = new WebAuthnLoginStrategy(
cache,

View File

@ -25,6 +25,11 @@ export class SsoLoginCredentials {
public codeVerifier: string,
public redirectUrl: string,
public orgId: string,
/**
* Optional email address for SSO login.
* Used for looking up 2FA token on clients that support remembering 2FA token.
*/
public email?: string,
public twoFactor?: TokenTwoFactorRequest,
) {}
}

View File

@ -114,7 +114,7 @@ describe("LoginStrategyService", () => {
token_type: "Bearer",
}),
);
tokenService.decodeToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
sub: "USER_ID",
name: "NAME",
email: "EMAIL",
@ -161,7 +161,7 @@ describe("LoginStrategyService", () => {
}),
);
tokenService.decodeToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
sub: "USER_ID",
name: "NAME",
email: "EMAIL",

View File

@ -0,0 +1,90 @@
import { DecodedAccessToken } from "@bitwarden/common/auth/services/token.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { decodeJwtTokenToJson } from "./decode-jwt-token-to-json.utility";
describe("decodeJwtTokenToJson", () => {
const accessTokenJwt =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0IiwibmJmIjoxNzA5MzI0MTExLCJpYXQiOjE3MDkzMjQxMTEsImV4cCI6MTcwOTMyNzcxMSwic2NvcGUiOlsiYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbIkFwcGxpY2F0aW9uIl0sImNsaWVudF9pZCI6IndlYiIsInN1YiI6ImVjZTcwYTEzLTcyMTYtNDNjNC05OTc3LWIxMDMwMTQ2ZTFlNyIsImF1dGhfdGltZSI6MTcwOTMyNDEwNCwiaWRwIjoiYml0d2FyZGVuIiwicHJlbWl1bSI6ZmFsc2UsImVtYWlsIjoiZXhhbXBsZUBiaXR3YXJkZW4uY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJzc3RhbXAiOiJHWTdKQU82NENLS1RLQkI2WkVBVVlMMldPUVU3QVNUMiIsIm5hbWUiOiJUZXN0IFVzZXIiLCJvcmdvd25lciI6WyI5MmI0OTkwOC1iNTE0LTQ1YTgtYmFkYi1iMTAzMDE0OGZlNTMiLCIzOGVkZTMyMi1iNGI0LTRiZDgtOWUwOS1iMTA3MDExMmRjMTEiLCJiMmQwNzAyOC1hNTgzLTRjM2UtOGQ2MC1iMTA3MDExOThjMjkiLCJiZjkzNGJhMi0wZmQ0LTQ5ZjItYTk1ZS1iMTA3MDExZmM5ZTYiLCJjMGI3Zjc1ZC0wMTVmLTQyYzktYjNhNi1iMTA4MDE3NjA3Y2EiXSwiZGV2aWNlIjoiNGI4NzIzNjctMGRhNi00MWEwLWFkY2ItNzdmMmZlZWZjNGY0IiwianRpIjoiNzUxNjFCRTQxMzFGRjVBMkRFNTExQjhDNEUyRkY4OUEifQ.n7roP8sSbfwcYdvRxZNZds27IK32TW6anorE6BORx_Q";
const accessTokenDecoded: DecodedAccessToken = {
iss: "http://localhost",
nbf: 1709324111,
iat: 1709324111,
exp: 1709327711,
scope: ["api", "offline_access"],
amr: ["Application"],
client_id: "web",
sub: "ece70a13-7216-43c4-9977-b1030146e1e7", // user id
auth_time: 1709324104,
idp: "bitwarden",
premium: false,
email: "example@bitwarden.com",
email_verified: false,
sstamp: "GY7JAO64CKKTKBB6ZEAUYL2WOQU7AST2",
name: "Test User",
orgowner: [
"92b49908-b514-45a8-badb-b1030148fe53",
"38ede322-b4b4-4bd8-9e09-b1070112dc11",
"b2d07028-a583-4c3e-8d60-b10701198c29",
"bf934ba2-0fd4-49f2-a95e-b107011fc9e6",
"c0b7f75d-015f-42c9-b3a6-b108017607ca",
],
device: "4b872367-0da6-41a0-adcb-77f2feefc4f4",
jti: "75161BE4131FF5A2DE511B8C4E2FF89A",
};
it("should decode the JWT token", () => {
// Act
const result = decodeJwtTokenToJson(accessTokenJwt);
// Assert
expect(result).toEqual(accessTokenDecoded);
});
it("should throw an error if the JWT token is null", () => {
// Act && Assert
expect(() => decodeJwtTokenToJson(null)).toThrow("JWT token not found");
});
it("should throw an error if the JWT token is missing 3 parts", () => {
// Act && Assert
expect(() => decodeJwtTokenToJson("invalidToken")).toThrow("JWT must have 3 parts");
});
it("should throw an error if the JWT token payload contains invalid JSON", () => {
// Arrange: Create a token with a valid format but with a payload that's valid Base64 but not valid JSON
const header = btoa(JSON.stringify({ alg: "none" }));
// Create a Base64-encoded string which fails to parse as JSON
const payload = btoa("invalid JSON");
const signature = "signature";
const malformedToken = `${header}.${payload}.${signature}`;
// Act & Assert
expect(() => decodeJwtTokenToJson(malformedToken)).toThrow(
"Cannot parse the token's payload into JSON",
);
});
it("should throw an error if the JWT token cannot be decoded", () => {
// Arrange: Create a token with a valid format
const header = btoa(JSON.stringify({ alg: "none" }));
const payload = "invalidPayloadBecauseWeWillMockTheFailure";
const signature = "signature";
const malformedToken = `${header}.${payload}.${signature}`;
// Mock Utils.fromUrlB64ToUtf8 to throw an error for this specific payload
jest.spyOn(Utils, "fromUrlB64ToUtf8").mockImplementation((input) => {
if (input === payload) {
throw new Error("Mock error");
}
return input; // Default behavior for other inputs
});
// Act & Assert
expect(() => decodeJwtTokenToJson(malformedToken)).toThrow("Cannot decode the token");
// Restore original function so other tests are not affected
jest.restoreAllMocks();
});
});

View File

@ -0,0 +1,32 @@
import { Utils } from "@bitwarden/common/platform/misc/utils";
export function decodeJwtTokenToJson(jwtToken: string): any {
if (jwtToken == null) {
throw new Error("JWT token not found");
}
const parts = jwtToken.split(".");
if (parts.length !== 3) {
throw new Error("JWT must have 3 parts");
}
// JWT has 3 parts: header, payload, signature separated by '.'
// So, grab the payload to decode
const encodedPayload = parts[1];
let decodedPayloadJSON: string;
try {
// Attempt to decode from URL-safe Base64 to UTF-8
decodedPayloadJSON = Utils.fromUrlB64ToUtf8(encodedPayload);
} catch (decodingError) {
throw new Error("Cannot decode the token");
}
try {
// Attempt to parse the JSON payload
const decodedToken = JSON.parse(decodedPayloadJSON);
return decodedToken;
} catch (jsonError) {
throw new Error("Cannot parse the token's payload into JSON");
}
}

View File

@ -0,0 +1 @@
export * from "./decode-jwt-token-to-json.utility";

View File

@ -54,6 +54,20 @@ export abstract class SsoLoginServiceAbstraction {
* Do not use this value outside of the SSO login flow.
*/
setOrganizationSsoIdentifier: (organizationIdentifier: string) => Promise<void>;
/**
* Gets the user's email.
* Note: This should only be used during the SSO flow to identify the user that is attempting to log in.
* @returns The user's email.
*/
getSsoEmail: () => Promise<string>;
/**
* Sets the user's email.
* Note: This should only be used during the SSO flow to identify the user that is attempting to log in.
* @param email The user's email.
* @returns A promise that resolves when the email has been set.
*
*/
setSsoEmail: (email: string) => Promise<void>;
/**
* Gets the value of the active user's organization sso identifier.
*

View File

@ -1,31 +1,208 @@
import { IdentityTokenResponse } from "../models/response/identity-token.response";
import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum";
import { UserId } from "../../types/guid";
import { DecodedAccessToken } from "../services/token.service";
export abstract class TokenService {
/**
* Sets the access token, refresh token, API Key Client ID, and API Key Client Secret in memory or disk
* based on the given vaultTimeoutAction and vaultTimeout and the derived access token user id.
* Note: for platforms that support secure storage, the access & refresh tokens are stored in secure storage instead of on disk.
* Note 2: this method also enforces always setting the access token and the refresh token together as
* we can retrieve the user id required to set the refresh token from the access token for efficiency.
* @param accessToken The access token to set.
* @param refreshToken The refresh token to set.
* @param clientIdClientSecret The API Key Client ID and Client Secret to set.
* @param vaultTimeoutAction The action to take when the vault times out.
* @param vaultTimeout The timeout for the vault.
* @returns A promise that resolves when the tokens have been set.
*/
setTokens: (
accessToken: string,
refreshToken: string,
clientIdClientSecret: [string, string],
) => Promise<any>;
setToken: (token: string) => Promise<any>;
getToken: () => Promise<string>;
setRefreshToken: (refreshToken: string) => Promise<any>;
getRefreshToken: () => Promise<string>;
setClientId: (clientId: string) => Promise<any>;
getClientId: () => Promise<string>;
setClientSecret: (clientSecret: string) => Promise<any>;
getClientSecret: () => Promise<string>;
setTwoFactorToken: (tokenResponse: IdentityTokenResponse) => Promise<any>;
getTwoFactorToken: () => Promise<string>;
clearTwoFactorToken: () => Promise<any>;
clearToken: (userId?: string) => Promise<any>;
decodeToken: (token?: string) => Promise<any>;
getTokenExpirationDate: () => Promise<Date>;
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
clientIdClientSecret?: [string, string],
) => Promise<void>;
/**
* Clears the access token, refresh token, API Key Client ID, and API Key Client Secret out of memory, disk, and secure storage if supported.
* @param userId The optional user id to clear the tokens for; if not provided, the active user id is used.
* @returns A promise that resolves when the tokens have been cleared.
*/
clearTokens: (userId?: UserId) => Promise<void>;
/**
* Sets the access token in memory or disk based on the given vaultTimeoutAction and vaultTimeout
* and the user id read off the access token
* Note: for platforms that support secure storage, the access & refresh tokens are stored in secure storage instead of on disk.
* @param accessToken The access token to set.
* @param vaultTimeoutAction The action to take when the vault times out.
* @param vaultTimeout The timeout for the vault.
* @returns A promise that resolves when the access token has been set.
*/
setAccessToken: (
accessToken: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
) => Promise<void>;
// TODO: revisit having this public clear method approach once the state service is fully deprecated.
/**
* Clears the access token for the given user id out of memory, disk, and secure storage if supported.
* @param userId The optional user id to clear the access token for; if not provided, the active user id is used.
* @returns A promise that resolves when the access token has been cleared.
*
* Note: This method is required so that the StateService doesn't have to inject the VaultTimeoutSettingsService to
* pass in the vaultTimeoutAction and vaultTimeout.
* This avoids a circular dependency between the StateService, TokenService, and VaultTimeoutSettingsService.
*/
clearAccessToken: (userId?: UserId) => Promise<void>;
/**
* Gets the access token
* @param userId - The optional user id to get the access token for; if not provided, the active user is used.
* @returns A promise that resolves with the access token or undefined.
*/
getAccessToken: (userId?: UserId) => Promise<string | undefined>;
/**
* Gets the refresh token.
* @param userId - The optional user id to get the refresh token for; if not provided, the active user is used.
* @returns A promise that resolves with the refresh token or undefined.
*/
getRefreshToken: (userId?: UserId) => Promise<string | undefined>;
/**
* Sets the API Key Client ID for the active user id in memory or disk based on the given vaultTimeoutAction and vaultTimeout.
* @param clientId The API Key Client ID to set.
* @param vaultTimeoutAction The action to take when the vault times out.
* @param vaultTimeout The timeout for the vault.
* @returns A promise that resolves when the API Key Client ID has been set.
*/
setClientId: (
clientId: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId?: UserId,
) => Promise<void>;
/**
* Gets the API Key Client ID for the active user.
* @returns A promise that resolves with the API Key Client ID or undefined
*/
getClientId: (userId?: UserId) => Promise<string | undefined>;
/**
* Sets the API Key Client Secret for the active user id in memory or disk based on the given vaultTimeoutAction and vaultTimeout.
* @param clientSecret The API Key Client Secret to set.
* @param vaultTimeoutAction The action to take when the vault times out.
* @param vaultTimeout The timeout for the vault.
* @returns A promise that resolves when the API Key Client Secret has been set.
*/
setClientSecret: (
clientSecret: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId?: UserId,
) => Promise<void>;
/**
* Gets the API Key Client Secret for the active user.
* @returns A promise that resolves with the API Key Client Secret or undefined
*/
getClientSecret: (userId?: UserId) => Promise<string | undefined>;
/**
* Sets the two factor token for the given email in global state.
* The two factor token is set when the user checks "remember me" when completing two factor
* authentication and it is used to bypass two factor authentication for a period of time.
* @param email The email to set the two factor token for.
* @param twoFactorToken The two factor token to set.
* @returns A promise that resolves when the two factor token has been set.
*/
setTwoFactorToken: (email: string, twoFactorToken: string) => Promise<void>;
/**
* Gets the two factor token for the given email.
* @param email The email to get the two factor token for.
* @returns A promise that resolves with the two factor token for the given email or null if it isn't found.
*/
getTwoFactorToken: (email: string) => Promise<string | null>;
/**
* Clears the two factor token for the given email out of global state.
* @param email The email to clear the two factor token for.
* @returns A promise that resolves when the two factor token has been cleared.
*/
clearTwoFactorToken: (email: string) => Promise<void>;
/**
* Decodes the access token.
* @param token The access token to decode.
* @returns A promise that resolves with the decoded access token.
*/
decodeAccessToken: (token?: string) => Promise<DecodedAccessToken>;
/**
* Gets the expiration date for the access token. Returns if token can't be decoded or has no expiration
* @returns A promise that resolves with the expiration date for the access token.
*/
getTokenExpirationDate: () => Promise<Date | null>;
/**
* Calculates the adjusted time in seconds until the access token expires, considering an optional offset.
*
* @param {number} [offsetSeconds=0] Optional seconds to subtract from the remaining time,
* creating a buffer before actual expiration. Useful for preemptive actions
* before token expiry. A value of 0 or omitting this parameter calculates time
* based on the actual expiration.
* @returns {Promise<number>} Promise resolving to the adjusted seconds remaining.
*/
tokenSecondsRemaining: (offsetSeconds?: number) => Promise<number>;
/**
* Checks if the access token needs to be refreshed.
* @param {number} [minutes=5] - Optional number of minutes before the access token expires to consider refreshing it.
* @returns A promise that resolves with a boolean indicating if the access token needs to be refreshed.
*/
tokenNeedsRefresh: (minutes?: number) => Promise<boolean>;
getUserId: () => Promise<string>;
/**
* Gets the user id for the active user from the access token.
* @returns A promise that resolves with the user id for the active user.
* @deprecated Use AccountService.activeAccount$ instead.
*/
getUserId: () => Promise<UserId>;
/**
* Gets the email for the active user from the access token.
* @returns A promise that resolves with the email for the active user.
* @deprecated Use AccountService.activeAccount$ instead.
*/
getEmail: () => Promise<string>;
/**
* Gets the email verified status for the active user from the access token.
* @returns A promise that resolves with the email verified status for the active user.
*/
getEmailVerified: () => Promise<boolean>;
/**
* Gets the name for the active user from the access token.
* @returns A promise that resolves with the name for the active user.
* @deprecated Use AccountService.activeAccount$ instead.
*/
getName: () => Promise<string>;
/**
* Gets the issuer for the active user from the access token.
* @returns A promise that resolves with the issuer for the active user.
*/
getIssuer: () => Promise<string>;
/**
* Gets whether or not the user authenticated via an external mechanism.
* @returns A promise that resolves with a boolean representing the user's external authN status.
*/
getIsExternal: () => Promise<boolean>;
}

View File

@ -7,6 +7,7 @@ import {
SSO_DISK,
StateProvider,
} from "../../platform/state";
import { SsoLoginServiceAbstraction } from "../abstractions/sso-login.service.abstraction";
/**
* Uses disk storage so that the code verifier can be persisted across sso redirects.
@ -33,16 +34,25 @@ const ORGANIZATION_SSO_IDENTIFIER = new KeyDefinition<string>(
},
);
export class SsoLoginService {
/**
* Uses disk storage so that the user's email can be persisted across sso redirects.
*/
const SSO_EMAIL = new KeyDefinition<string>(SSO_DISK, "ssoEmail", {
deserializer: (state) => state,
});
export class SsoLoginService implements SsoLoginServiceAbstraction {
private codeVerifierState: GlobalState<string>;
private ssoState: GlobalState<string>;
private orgSsoIdentifierState: GlobalState<string>;
private ssoEmailState: GlobalState<string>;
private activeUserOrgSsoIdentifierState: ActiveUserState<string>;
constructor(private stateProvider: StateProvider) {
this.codeVerifierState = this.stateProvider.getGlobal(CODE_VERIFIER);
this.ssoState = this.stateProvider.getGlobal(SSO_STATE);
this.orgSsoIdentifierState = this.stateProvider.getGlobal(ORGANIZATION_SSO_IDENTIFIER);
this.ssoEmailState = this.stateProvider.getGlobal(SSO_EMAIL);
this.activeUserOrgSsoIdentifierState = this.stateProvider.getActive(
ORGANIZATION_SSO_IDENTIFIER,
);
@ -72,6 +82,14 @@ export class SsoLoginService {
await this.orgSsoIdentifierState.update((_) => organizationIdentifier);
}
getSsoEmail(): Promise<string> {
return firstValueFrom(this.ssoEmailState.state$);
}
async setSsoEmail(email: string): Promise<void> {
await this.ssoEmailState.update((_) => email);
}
getActiveUserOrganizationSsoIdentifier(): Promise<string> {
return firstValueFrom(this.activeUserOrgSsoIdentifierState.state$);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,125 +1,629 @@
import { StateService } from "../../platform/abstractions/state.service";
import { Utils } from "../../platform/misc/utils";
import { firstValueFrom } from "rxjs";
import { decodeJwtTokenToJson } from "@bitwarden/auth/common";
import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum";
import { AbstractStorageService } from "../../platform/abstractions/storage.service";
import { StorageLocation } from "../../platform/enums";
import { StorageOptions } from "../../platform/models/domain/storage-options";
import {
GlobalState,
GlobalStateProvider,
KeyDefinition,
SingleUserStateProvider,
} from "../../platform/state";
import { UserId } from "../../types/guid";
import { TokenService as TokenServiceAbstraction } from "../abstractions/token.service";
import { IdentityTokenResponse } from "../models/response/identity-token.response";
import { ACCOUNT_ACTIVE_ACCOUNT_ID } from "./account.service";
import {
ACCESS_TOKEN_DISK,
ACCESS_TOKEN_MEMORY,
ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE,
API_KEY_CLIENT_ID_DISK,
API_KEY_CLIENT_ID_MEMORY,
API_KEY_CLIENT_SECRET_DISK,
API_KEY_CLIENT_SECRET_MEMORY,
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
REFRESH_TOKEN_DISK,
REFRESH_TOKEN_MEMORY,
REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE,
} from "./token.state";
export enum TokenStorageLocation {
Disk = "disk",
SecureStorage = "secureStorage",
Memory = "memory",
}
/**
* Type representing the structure of a standard Bitwarden decoded access token.
* src: https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
* Note: all claims are technically optional so we must verify their existence before using them.
* Note 2: NumericDate is a number representing a date in seconds since the Unix epoch.
*/
export type DecodedAccessToken = {
/** Issuer - the issuer of the token, typically the URL of the authentication server */
iss?: string;
/** Not Before - a timestamp defining when the token starts being valid */
nbf?: number;
/** Issued At - a timestamp of when the token was issued */
iat?: number;
/** Expiration Time - a NumericDate timestamp of when the token will expire */
exp?: number;
/** Scope - the scope of the access request, such as the permissions the token grants */
scope?: string[];
/** Authentication Method Reference - the methods used in the authentication */
amr?: string[];
/** Client ID - the identifier for the client that requested the token */
client_id?: string;
/** Subject - the unique identifier for the user */
sub?: string;
/** Authentication Time - a timestamp of when the user authentication occurred */
auth_time?: number;
/** Identity Provider - the system or service that authenticated the user */
idp?: string;
/** Premium - a boolean flag indicating whether the account is premium */
premium?: boolean;
/** Email - the user's email address */
email?: string;
/** Email Verified - a boolean flag indicating whether the user's email address has been verified */
email_verified?: boolean;
/**
* Security Stamp - a unique identifier which invalidates the access token if it changes in the db
* (typically after critical account changes like a password change)
*/
sstamp?: string;
/** Name - the name of the user */
name?: string;
/** Organization Owners - a list of organization owner identifiers */
orgowner?: string[];
/** Device - the identifier of the device used */
device?: string;
/** JWT ID - a unique identifier for the JWT */
jti?: string;
};
export class TokenService implements TokenServiceAbstraction {
static decodeToken(token: string): Promise<any> {
if (token == null) {
throw new Error("Token not provided.");
private readonly accessTokenSecureStorageKey: string = "_accessToken";
private readonly refreshTokenSecureStorageKey: string = "_refreshToken";
private emailTwoFactorTokenRecordGlobalState: GlobalState<Record<string, string>>;
private activeUserIdGlobalState: GlobalState<UserId>;
constructor(
// Note: we cannot use ActiveStateProvider because if we ever want to inject
// this service into the AccountService, we will make a circular dependency
private singleUserStateProvider: SingleUserStateProvider,
private globalStateProvider: GlobalStateProvider,
private readonly platformSupportsSecureStorage: boolean,
private secureStorageService: AbstractStorageService,
) {
this.initializeState();
}
const parts = token.split(".");
if (parts.length !== 3) {
throw new Error("JWT must have 3 parts");
}
private initializeState(): void {
this.emailTwoFactorTokenRecordGlobalState = this.globalStateProvider.get(
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
);
const decoded = Utils.fromUrlB64ToUtf8(parts[1]);
if (decoded == null) {
throw new Error("Cannot decode the token");
this.activeUserIdGlobalState = this.globalStateProvider.get(ACCOUNT_ACTIVE_ACCOUNT_ID);
}
const decodedToken = JSON.parse(decoded);
return decodedToken;
}
constructor(private stateService: StateService) {}
async setTokens(
accessToken: string,
refreshToken: string,
clientIdClientSecret: [string, string],
): Promise<any> {
await this.setToken(accessToken);
await this.setRefreshToken(refreshToken);
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
clientIdClientSecret?: [string, string],
): Promise<void> {
if (!accessToken || !refreshToken) {
throw new Error("Access token and refresh token are required.");
}
// get user id the access token
const userId: UserId = await this.getUserIdFromAccessToken(accessToken);
if (!userId) {
throw new Error("User id not found. Cannot set tokens.");
}
await this._setAccessToken(accessToken, vaultTimeoutAction, vaultTimeout, userId);
await this.setRefreshToken(refreshToken, vaultTimeoutAction, vaultTimeout, userId);
if (clientIdClientSecret != null) {
await this.setClientId(clientIdClientSecret[0]);
await this.setClientSecret(clientIdClientSecret[1]);
await this.setClientId(clientIdClientSecret[0], vaultTimeoutAction, vaultTimeout, userId);
await this.setClientSecret(clientIdClientSecret[1], vaultTimeoutAction, vaultTimeout, userId);
}
}
async setClientId(clientId: string): Promise<any> {
return await this.stateService.setApiKeyClientId(clientId);
/**
* Internal helper for set access token which always requires user id.
* This is useful because setTokens always will have a user id from the access token whereas
* the public setAccessToken method does not.
*/
private async _setAccessToken(
accessToken: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId: UserId,
): Promise<void> {
const storageLocation = await this.determineStorageLocation(
vaultTimeoutAction,
vaultTimeout,
true,
);
switch (storageLocation) {
case TokenStorageLocation.SecureStorage:
await this.saveStringToSecureStorage(userId, this.accessTokenSecureStorageKey, accessToken);
// TODO: PM-6408 - https://bitwarden.atlassian.net/browse/PM-6408
// 2024-02-20: Remove access token from memory and disk so that we migrate to secure storage over time.
// Remove these 2 calls to remove the access token from memory and disk after 3 releases.
await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_DISK).update((_) => null);
await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MEMORY).update((_) => null);
// Set flag to indicate that the access token has been migrated to secure storage (don't remove this)
await this.setAccessTokenMigratedToSecureStorage(userId);
return;
case TokenStorageLocation.Disk:
await this.singleUserStateProvider
.get(userId, ACCESS_TOKEN_DISK)
.update((_) => accessToken);
return;
case TokenStorageLocation.Memory:
await this.singleUserStateProvider
.get(userId, ACCESS_TOKEN_MEMORY)
.update((_) => accessToken);
return;
}
}
async getClientId(): Promise<string> {
return await this.stateService.getApiKeyClientId();
async setAccessToken(
accessToken: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
): Promise<void> {
if (!accessToken) {
throw new Error("Access token is required.");
}
const userId: UserId = await this.getUserIdFromAccessToken(accessToken);
// If we don't have a user id, we can't save the value
if (!userId) {
throw new Error("User id not found. Cannot save access token.");
}
async setClientSecret(clientSecret: string): Promise<any> {
return await this.stateService.setApiKeyClientSecret(clientSecret);
await this._setAccessToken(accessToken, vaultTimeoutAction, vaultTimeout, userId);
}
async getClientSecret(): Promise<string> {
return await this.stateService.getApiKeyClientSecret();
async clearAccessToken(userId?: UserId): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
// If we don't have a user id, we can't clear the value
if (!userId) {
throw new Error("User id not found. Cannot clear access token.");
}
async setToken(token: string): Promise<void> {
await this.stateService.setAccessToken(token);
// TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data.
// we can't determine storage location w/out vaultTimeoutAction and vaultTimeout
// but we can simply clear all locations to avoid the need to require those parameters
if (this.platformSupportsSecureStorage) {
await this.secureStorageService.remove(
`${userId}${this.accessTokenSecureStorageKey}`,
this.getSecureStorageOptions(userId),
);
}
async getToken(): Promise<string> {
return await this.stateService.getAccessToken();
// Platform doesn't support secure storage, so use state provider implementation
await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_DISK).update((_) => null);
await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MEMORY).update((_) => null);
}
async setRefreshToken(refreshToken: string): Promise<any> {
return await this.stateService.setRefreshToken(refreshToken);
async getAccessToken(userId?: UserId): Promise<string | undefined> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
return undefined;
}
async getRefreshToken(): Promise<string> {
return await this.stateService.getRefreshToken();
const accessTokenMigratedToSecureStorage =
await this.getAccessTokenMigratedToSecureStorage(userId);
if (this.platformSupportsSecureStorage && accessTokenMigratedToSecureStorage) {
return await this.getStringFromSecureStorage(userId, this.accessTokenSecureStorageKey);
}
async setTwoFactorToken(tokenResponse: IdentityTokenResponse): Promise<any> {
return await this.stateService.setTwoFactorToken(tokenResponse.twoFactorToken);
// Try to get the access token from memory
const accessTokenMemory = await this.getStateValueByUserIdAndKeyDef(
userId,
ACCESS_TOKEN_MEMORY,
);
if (accessTokenMemory != null) {
return accessTokenMemory;
}
async getTwoFactorToken(): Promise<string> {
return await this.stateService.getTwoFactorToken();
// If memory is null, read from disk
return await this.getStateValueByUserIdAndKeyDef(userId, ACCESS_TOKEN_DISK);
}
async clearTwoFactorToken(): Promise<any> {
return await this.stateService.setTwoFactorToken(null);
private async getAccessTokenMigratedToSecureStorage(userId: UserId): Promise<boolean> {
return await firstValueFrom(
this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE).state$,
);
}
async clearToken(userId?: string): Promise<any> {
await this.stateService.setAccessToken(null, { userId: userId });
await this.stateService.setRefreshToken(null, { userId: userId });
await this.stateService.setApiKeyClientId(null, { userId: userId });
await this.stateService.setApiKeyClientSecret(null, { userId: userId });
private async setAccessTokenMigratedToSecureStorage(userId: UserId): Promise<void> {
await this.singleUserStateProvider
.get(userId, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE)
.update((_) => true);
}
// Private because we only ever set the refresh token when also setting the access token
// and we need the user id from the access token to save to secure storage
private async setRefreshToken(
refreshToken: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId: UserId,
): Promise<void> {
// If we don't have a user id, we can't save the value
if (!userId) {
throw new Error("User id not found. Cannot save refresh token.");
}
const storageLocation = await this.determineStorageLocation(
vaultTimeoutAction,
vaultTimeout,
true,
);
switch (storageLocation) {
case TokenStorageLocation.SecureStorage:
await this.saveStringToSecureStorage(
userId,
this.refreshTokenSecureStorageKey,
refreshToken,
);
// TODO: PM-6408 - https://bitwarden.atlassian.net/browse/PM-6408
// 2024-02-20: Remove refresh token from memory and disk so that we migrate to secure storage over time.
// Remove these 2 calls to remove the refresh token from memory and disk after 3 releases.
await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_DISK).update((_) => null);
await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MEMORY).update((_) => null);
// Set flag to indicate that the refresh token has been migrated to secure storage (don't remove this)
await this.setRefreshTokenMigratedToSecureStorage(userId);
return;
case TokenStorageLocation.Disk:
await this.singleUserStateProvider
.get(userId, REFRESH_TOKEN_DISK)
.update((_) => refreshToken);
return;
case TokenStorageLocation.Memory:
await this.singleUserStateProvider
.get(userId, REFRESH_TOKEN_MEMORY)
.update((_) => refreshToken);
return;
}
}
async getRefreshToken(userId?: UserId): Promise<string | undefined> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
return undefined;
}
const refreshTokenMigratedToSecureStorage =
await this.getRefreshTokenMigratedToSecureStorage(userId);
if (this.platformSupportsSecureStorage && refreshTokenMigratedToSecureStorage) {
return await this.getStringFromSecureStorage(userId, this.refreshTokenSecureStorageKey);
}
// pre-secure storage migration:
// Always read memory first b/c faster
const refreshTokenMemory = await this.getStateValueByUserIdAndKeyDef(
userId,
REFRESH_TOKEN_MEMORY,
);
if (refreshTokenMemory != null) {
return refreshTokenMemory;
}
// if memory is null, read from disk
const refreshTokenDisk = await this.getStateValueByUserIdAndKeyDef(userId, REFRESH_TOKEN_DISK);
if (refreshTokenDisk != null) {
return refreshTokenDisk;
}
return null;
}
private async clearRefreshToken(userId: UserId): Promise<void> {
// If we don't have a user id, we can't clear the value
if (!userId) {
throw new Error("User id not found. Cannot clear refresh token.");
}
// TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data.
// we can't determine storage location w/out vaultTimeoutAction and vaultTimeout
// but we can simply clear all locations to avoid the need to require those parameters
if (this.platformSupportsSecureStorage) {
await this.secureStorageService.remove(
`${userId}${this.refreshTokenSecureStorageKey}`,
this.getSecureStorageOptions(userId),
);
}
// Platform doesn't support secure storage, so use state provider implementation
await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MEMORY).update((_) => null);
await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_DISK).update((_) => null);
}
private async getRefreshTokenMigratedToSecureStorage(userId: UserId): Promise<boolean> {
return await firstValueFrom(
this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE).state$,
);
}
private async setRefreshTokenMigratedToSecureStorage(userId: UserId): Promise<void> {
await this.singleUserStateProvider
.get(userId, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE)
.update((_) => true);
}
async setClientId(
clientId: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId?: UserId,
): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
// If we don't have a user id, we can't save the value
if (!userId) {
throw new Error("User id not found. Cannot save client id.");
}
const storageLocation = await this.determineStorageLocation(
vaultTimeoutAction,
vaultTimeout,
false,
);
if (storageLocation === TokenStorageLocation.Disk) {
await this.singleUserStateProvider
.get(userId, API_KEY_CLIENT_ID_DISK)
.update((_) => clientId);
} else if (storageLocation === TokenStorageLocation.Memory) {
await this.singleUserStateProvider
.get(userId, API_KEY_CLIENT_ID_MEMORY)
.update((_) => clientId);
}
}
async getClientId(userId?: UserId): Promise<string | undefined> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
return undefined;
}
// Always read memory first b/c faster
const apiKeyClientIdMemory = await this.getStateValueByUserIdAndKeyDef(
userId,
API_KEY_CLIENT_ID_MEMORY,
);
if (apiKeyClientIdMemory != null) {
return apiKeyClientIdMemory;
}
// if memory is null, read from disk
return await this.getStateValueByUserIdAndKeyDef(userId, API_KEY_CLIENT_ID_DISK);
}
private async clearClientId(userId?: UserId): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
// If we don't have a user id, we can't clear the value
if (!userId) {
throw new Error("User id not found. Cannot clear client id.");
}
// TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data.
// we can't determine storage location w/out vaultTimeoutAction and vaultTimeout
// but we can simply clear both locations to avoid the need to require those parameters
// Platform doesn't support secure storage, so use state provider implementation
await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_ID_MEMORY).update((_) => null);
await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_ID_DISK).update((_) => null);
}
async setClientSecret(
clientSecret: string,
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
userId?: UserId,
): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
throw new Error("User id not found. Cannot save client secret.");
}
const storageLocation = await this.determineStorageLocation(
vaultTimeoutAction,
vaultTimeout,
false,
);
if (storageLocation === TokenStorageLocation.Disk) {
await this.singleUserStateProvider
.get(userId, API_KEY_CLIENT_SECRET_DISK)
.update((_) => clientSecret);
} else if (storageLocation === TokenStorageLocation.Memory) {
await this.singleUserStateProvider
.get(userId, API_KEY_CLIENT_SECRET_MEMORY)
.update((_) => clientSecret);
}
}
async getClientSecret(userId?: UserId): Promise<string | undefined> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
return undefined;
}
// Always read memory first b/c faster
const apiKeyClientSecretMemory = await this.getStateValueByUserIdAndKeyDef(
userId,
API_KEY_CLIENT_SECRET_MEMORY,
);
if (apiKeyClientSecretMemory != null) {
return apiKeyClientSecretMemory;
}
// if memory is null, read from disk
return await this.getStateValueByUserIdAndKeyDef(userId, API_KEY_CLIENT_SECRET_DISK);
}
private async clearClientSecret(userId?: UserId): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
// If we don't have a user id, we can't clear the value
if (!userId) {
throw new Error("User id not found. Cannot clear client secret.");
}
// TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data.
// we can't determine storage location w/out vaultTimeoutAction and vaultTimeout
// but we can simply clear both locations to avoid the need to require those parameters
// Platform doesn't support secure storage, so use state provider implementation
await this.singleUserStateProvider
.get(userId, API_KEY_CLIENT_SECRET_MEMORY)
.update((_) => null);
await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_SECRET_DISK).update((_) => null);
}
async setTwoFactorToken(email: string, twoFactorToken: string): Promise<void> {
await this.emailTwoFactorTokenRecordGlobalState.update((emailTwoFactorTokenRecord) => {
emailTwoFactorTokenRecord ??= {};
emailTwoFactorTokenRecord[email] = twoFactorToken;
return emailTwoFactorTokenRecord;
});
}
async getTwoFactorToken(email: string): Promise<string | null> {
const emailTwoFactorTokenRecord: Record<string, string> = await firstValueFrom(
this.emailTwoFactorTokenRecordGlobalState.state$,
);
if (!emailTwoFactorTokenRecord) {
return null;
}
return emailTwoFactorTokenRecord[email];
}
async clearTwoFactorToken(email: string): Promise<void> {
await this.emailTwoFactorTokenRecordGlobalState.update((emailTwoFactorTokenRecord) => {
emailTwoFactorTokenRecord ??= {};
delete emailTwoFactorTokenRecord[email];
return emailTwoFactorTokenRecord;
});
}
async clearTokens(userId?: UserId): Promise<void> {
userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$);
if (!userId) {
throw new Error("User id not found. Cannot clear tokens.");
}
await Promise.all([
this.clearAccessToken(userId),
this.clearRefreshToken(userId),
this.clearClientId(userId),
this.clearClientSecret(userId),
]);
}
// jwthelper methods
// ref https://github.com/auth0/angular-jwt/blob/master/src/angularJwt/services/jwt.js
async decodeToken(token?: string): Promise<any> {
token = token ?? (await this.stateService.getAccessToken());
async decodeAccessToken(token?: string): Promise<DecodedAccessToken> {
token = token ?? (await this.getAccessToken());
if (token == null) {
throw new Error("Token not found.");
throw new Error("Access token not found.");
}
return TokenService.decodeToken(token);
return decodeJwtTokenToJson(token) as DecodedAccessToken;
}
async getTokenExpirationDate(): Promise<Date> {
const decoded = await this.decodeToken();
if (typeof decoded.exp === "undefined") {
// TODO: PM-6678- tech debt - consider consolidating the return types of all these access
// token data retrieval methods to return null if something goes wrong instead of throwing an error.
async getTokenExpirationDate(): Promise<Date | null> {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
// per RFC, exp claim is optional but if it exists, it should be a number
if (!decoded || typeof decoded.exp !== "number") {
return null;
}
const d = new Date(0); // The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);
return d;
// The 0 in Date(0) is the key; it sets the date to the epoch
const expirationDate = new Date(0);
expirationDate.setUTCSeconds(decoded.exp);
return expirationDate;
}
async tokenSecondsRemaining(offsetSeconds = 0): Promise<number> {
const d = await this.getTokenExpirationDate();
if (d == null) {
const date = await this.getTokenExpirationDate();
if (date == null) {
return 0;
}
const msRemaining = d.valueOf() - (new Date().valueOf() + offsetSeconds * 1000);
const msRemaining = date.valueOf() - (new Date().valueOf() + offsetSeconds * 1000);
return Math.round(msRemaining / 1000);
}
@ -128,54 +632,159 @@ export class TokenService implements TokenServiceAbstraction {
return sRemaining < 60 * minutes;
}
async getUserId(): Promise<string> {
const decoded = await this.decodeToken();
if (typeof decoded.sub === "undefined") {
async getUserId(): Promise<UserId> {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.sub !== "string") {
throw new Error("No user id found");
}
return decoded.sub as string;
return decoded.sub as UserId;
}
private async getUserIdFromAccessToken(accessToken: string): Promise<UserId> {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken(accessToken);
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.sub !== "string") {
throw new Error("No user id found");
}
return decoded.sub as UserId;
}
async getEmail(): Promise<string> {
const decoded = await this.decodeToken();
if (typeof decoded.email === "undefined") {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.email !== "string") {
throw new Error("No email found");
}
return decoded.email as string;
return decoded.email;
}
async getEmailVerified(): Promise<boolean> {
const decoded = await this.decodeToken();
if (typeof decoded.email_verified === "undefined") {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.email_verified !== "boolean") {
throw new Error("No email verification found");
}
return decoded.email_verified as boolean;
return decoded.email_verified;
}
async getName(): Promise<string> {
const decoded = await this.decodeToken();
if (typeof decoded.name === "undefined") {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.name !== "string") {
return null;
}
return decoded.name as string;
return decoded.name;
}
async getIssuer(): Promise<string> {
const decoded = await this.decodeToken();
if (typeof decoded.iss === "undefined") {
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
if (!decoded || typeof decoded.iss !== "string") {
throw new Error("No issuer found");
}
return decoded.iss as string;
return decoded.iss;
}
async getIsExternal(): Promise<boolean> {
const decoded = await this.decodeToken();
let decoded: DecodedAccessToken;
try {
decoded = await this.decodeAccessToken();
} catch (error) {
throw new Error("Failed to decode access token: " + error.message);
}
return Array.isArray(decoded.amr) && decoded.amr.includes("external");
}
private async getStateValueByUserIdAndKeyDef(
userId: UserId,
storageLocation: KeyDefinition<string>,
): Promise<string | undefined> {
// read from single user state provider
return await firstValueFrom(this.singleUserStateProvider.get(userId, storageLocation).state$);
}
private async determineStorageLocation(
vaultTimeoutAction: VaultTimeoutAction,
vaultTimeout: number | null,
useSecureStorage: boolean,
): Promise<TokenStorageLocation> {
if (vaultTimeoutAction === VaultTimeoutAction.LogOut && vaultTimeout != null) {
return TokenStorageLocation.Memory;
} else {
if (useSecureStorage && this.platformSupportsSecureStorage) {
return TokenStorageLocation.SecureStorage;
}
return TokenStorageLocation.Disk;
}
}
private async saveStringToSecureStorage(
userId: UserId,
storageKey: string,
value: string,
): Promise<void> {
await this.secureStorageService.save<string>(
`${userId}${storageKey}`,
value,
this.getSecureStorageOptions(userId),
);
}
private async getStringFromSecureStorage(
userId: UserId,
storageKey: string,
): Promise<string | null> {
// If we have a user ID, read from secure storage.
return await this.secureStorageService.get<string>(
`${userId}${storageKey}`,
this.getSecureStorageOptions(userId),
);
}
private getSecureStorageOptions(userId: UserId): StorageOptions {
return {
storageLocation: StorageLocation.Disk,
useSecureStorage: true,
userId: userId,
};
}
}

View File

@ -0,0 +1,64 @@
import { KeyDefinition } from "../../platform/state";
import {
ACCESS_TOKEN_DISK,
ACCESS_TOKEN_MEMORY,
ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE,
API_KEY_CLIENT_ID_DISK,
API_KEY_CLIENT_ID_MEMORY,
API_KEY_CLIENT_SECRET_DISK,
API_KEY_CLIENT_SECRET_MEMORY,
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
REFRESH_TOKEN_DISK,
REFRESH_TOKEN_MEMORY,
REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE,
} from "./token.state";
describe.each([
[ACCESS_TOKEN_DISK, "accessTokenDisk"],
[ACCESS_TOKEN_MEMORY, "accessTokenMemory"],
[ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, true],
[REFRESH_TOKEN_DISK, "refreshTokenDisk"],
[REFRESH_TOKEN_MEMORY, "refreshTokenMemory"],
[REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, true],
[EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, { user: "token" }],
[API_KEY_CLIENT_ID_DISK, "apiKeyClientIdDisk"],
[API_KEY_CLIENT_ID_MEMORY, "apiKeyClientIdMemory"],
[API_KEY_CLIENT_SECRET_DISK, "apiKeyClientSecretDisk"],
[API_KEY_CLIENT_SECRET_MEMORY, "apiKeyClientSecretMemory"],
])(
"deserializes state key definitions",
(
keyDefinition:
| KeyDefinition<string>
| KeyDefinition<boolean>
| KeyDefinition<Record<string, string>>,
state: string | boolean | Record<string, string>,
) => {
function getTypeDescription(value: any): string {
if (isRecord(value)) {
return "Record<string, string>";
} else if (Array.isArray(value)) {
return "array";
} else if (value === null) {
return "null";
}
// Fallback for primitive types
return typeof value;
}
function isRecord(value: any): value is Record<string, string> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function testDeserialization<T>(keyDefinition: KeyDefinition<T>, state: T) {
const deserialized = keyDefinition.deserializer(JSON.parse(JSON.stringify(state)));
expect(deserialized).toEqual(state);
}
it(`should deserialize state for KeyDefinition<${getTypeDescription(state)}>: "${keyDefinition.key}"`, () => {
testDeserialization(keyDefinition, state);
});
},
);

View File

@ -0,0 +1,65 @@
import { KeyDefinition, TOKEN_DISK, TOKEN_DISK_LOCAL, TOKEN_MEMORY } from "../../platform/state";
export const ACCESS_TOKEN_DISK = new KeyDefinition<string>(TOKEN_DISK, "accessToken", {
deserializer: (accessToken) => accessToken,
});
export const ACCESS_TOKEN_MEMORY = new KeyDefinition<string>(TOKEN_MEMORY, "accessToken", {
deserializer: (accessToken) => accessToken,
});
export const ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE = new KeyDefinition<boolean>(
TOKEN_DISK,
"accessTokenMigratedToSecureStorage",
{
deserializer: (accessTokenMigratedToSecureStorage) => accessTokenMigratedToSecureStorage,
},
);
export const REFRESH_TOKEN_DISK = new KeyDefinition<string>(TOKEN_DISK, "refreshToken", {
deserializer: (refreshToken) => refreshToken,
});
export const REFRESH_TOKEN_MEMORY = new KeyDefinition<string>(TOKEN_MEMORY, "refreshToken", {
deserializer: (refreshToken) => refreshToken,
});
export const REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE = new KeyDefinition<boolean>(
TOKEN_DISK,
"refreshTokenMigratedToSecureStorage",
{
deserializer: (refreshTokenMigratedToSecureStorage) => refreshTokenMigratedToSecureStorage,
},
);
export const EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL = KeyDefinition.record<string, string>(
TOKEN_DISK_LOCAL,
"emailTwoFactorTokenRecord",
{
deserializer: (emailTwoFactorTokenRecord) => emailTwoFactorTokenRecord,
},
);
export const API_KEY_CLIENT_ID_DISK = new KeyDefinition<string>(TOKEN_DISK, "apiKeyClientId", {
deserializer: (apiKeyClientId) => apiKeyClientId,
});
export const API_KEY_CLIENT_ID_MEMORY = new KeyDefinition<string>(TOKEN_MEMORY, "apiKeyClientId", {
deserializer: (apiKeyClientId) => apiKeyClientId,
});
export const API_KEY_CLIENT_SECRET_DISK = new KeyDefinition<string>(
TOKEN_DISK,
"apiKeyClientSecret",
{
deserializer: (apiKeyClientSecret) => apiKeyClientSecret,
},
);
export const API_KEY_CLIENT_SECRET_MEMORY = new KeyDefinition<string>(
TOKEN_MEMORY,
"apiKeyClientSecret",
{
deserializer: (apiKeyClientSecret) => apiKeyClientSecret,
},
);

View File

@ -52,16 +52,11 @@ export abstract class StateService<T extends Account = Account> {
clean: (options?: StorageOptions) => Promise<UserId>;
init: (initOptions?: InitOptions) => Promise<void>;
getAccessToken: (options?: StorageOptions) => Promise<string>;
setAccessToken: (value: string, options?: StorageOptions) => Promise<void>;
getAddEditCipherInfo: (options?: StorageOptions) => Promise<AddEditCipherInfo>;
setAddEditCipherInfo: (value: AddEditCipherInfo, options?: StorageOptions) => Promise<void>;
getAlwaysShowDock: (options?: StorageOptions) => Promise<boolean>;
setAlwaysShowDock: (value: boolean, options?: StorageOptions) => Promise<void>;
getApiKeyClientId: (options?: StorageOptions) => Promise<string>;
setApiKeyClientId: (value: string, options?: StorageOptions) => Promise<void>;
getApiKeyClientSecret: (options?: StorageOptions) => Promise<string>;
setApiKeyClientSecret: (value: string, options?: StorageOptions) => Promise<void>;
getAutoConfirmFingerPrints: (options?: StorageOptions) => Promise<boolean>;
setAutoConfirmFingerprints: (value: boolean, options?: StorageOptions) => Promise<void>;
getBiometricFingerprintValidated: (options?: StorageOptions) => Promise<boolean>;
@ -332,14 +327,10 @@ export abstract class StateService<T extends Account = Account> {
* Sets the user's Pin, encrypted by the user key
*/
setProtectedPin: (value: string, options?: StorageOptions) => Promise<void>;
getRefreshToken: (options?: StorageOptions) => Promise<string>;
setRefreshToken: (value: string, options?: StorageOptions) => Promise<void>;
getRememberedEmail: (options?: StorageOptions) => Promise<string>;
setRememberedEmail: (value: string, options?: StorageOptions) => Promise<void>;
getSecurityStamp: (options?: StorageOptions) => Promise<string>;
setSecurityStamp: (value: string, options?: StorageOptions) => Promise<void>;
getTwoFactorToken: (options?: StorageOptions) => Promise<string>;
setTwoFactorToken: (value: string, options?: StorageOptions) => Promise<void>;
getUserId: (options?: StorageOptions) => Promise<string>;
getUsesKeyConnector: (options?: StorageOptions) => Promise<boolean>;
setUsesKeyConnector: (value: boolean, options?: StorageOptions) => Promise<void>;

View File

@ -112,7 +112,6 @@ export class AccountKeys {
masterKeyEncryptedUserKey?: string;
deviceKey?: ReturnType<SymmetricCryptoKey["toJSON"]>;
publicKey?: Uint8Array;
apiKeyClientSecret?: string;
/** @deprecated July 2023, left for migration purposes*/
cryptoMasterKey?: SymmetricCryptoKey;
@ -167,7 +166,6 @@ export class AccountKeys {
}
export class AccountProfile {
apiKeyClientId?: string;
convertAccountToKeyConnector?: boolean;
name?: string;
email?: string;
@ -233,8 +231,6 @@ export class AccountSettings {
}
export class AccountTokens {
accessToken?: string;
refreshToken?: string;
securityStamp?: string;
static fromJSON(obj: Jsonify<AccountTokens>): AccountTokens {

View File

@ -3,12 +3,12 @@ import { Jsonify, JsonValue } from "type-fest";
import { OrganizationData } from "../../admin-console/models/data/organization.data";
import { AccountService } from "../../auth/abstractions/account.service";
import { TokenService } from "../../auth/abstractions/token.service";
import { AuthenticationStatus } from "../../auth/enums/authentication-status";
import { AdminAuthRequestStorable } from "../../auth/models/domain/admin-auth-req-storable";
import { ForceSetPasswordReason } from "../../auth/models/domain/force-set-password-reason";
import { KdfConfig } from "../../auth/models/domain/kdf-config";
import { BiometricKey } from "../../auth/types/biometric-key";
import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum";
import { EventData } from "../../models/data/event.data";
import { WindowState } from "../../models/domain/window-state";
import { GeneratorOptions } from "../../tools/generator/generator-options";
@ -100,6 +100,7 @@ export class StateService<
protected stateFactory: StateFactory<TGlobalState, TAccount>,
protected accountService: AccountService,
protected environmentService: EnvironmentService,
protected tokenService: TokenService,
private migrationRunner: MigrationRunner,
protected useAccountCache: boolean = true,
) {
@ -190,7 +191,7 @@ export class StateService<
// TODO: Temporary update to avoid routing all account status changes through account service for now.
// The determination of state should be handled by the various services that control those values.
const token = await this.getAccessToken({ userId: userId });
const token = await this.tokenService.getAccessToken(userId as UserId);
const autoKey = await this.getUserKeyAutoUnlock({ userId: userId });
const accountStatus =
token == null
@ -255,18 +256,6 @@ export class StateService<
return currentUser as UserId;
}
async getAccessToken(options?: StorageOptions): Promise<string> {
options = await this.getTimeoutBasedStorageOptions(options);
return (await this.getAccount(options))?.tokens?.accessToken;
}
async setAccessToken(value: string, options?: StorageOptions): Promise<void> {
options = await this.getTimeoutBasedStorageOptions(options);
const account = await this.getAccount(options);
account.tokens.accessToken = value;
await this.saveAccount(account, options);
}
async getAddEditCipherInfo(options?: StorageOptions): Promise<AddEditCipherInfo> {
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultInMemoryOptions()),
@ -313,30 +302,6 @@ export class StateService<
);
}
async getApiKeyClientId(options?: StorageOptions): Promise<string> {
options = await this.getTimeoutBasedStorageOptions(options);
return (await this.getAccount(options))?.profile?.apiKeyClientId;
}
async setApiKeyClientId(value: string, options?: StorageOptions): Promise<void> {
options = await this.getTimeoutBasedStorageOptions(options);
const account = await this.getAccount(options);
account.profile.apiKeyClientId = value;
await this.saveAccount(account, options);
}
async getApiKeyClientSecret(options?: StorageOptions): Promise<string> {
options = await this.getTimeoutBasedStorageOptions(options);
return (await this.getAccount(options))?.keys?.apiKeyClientSecret;
}
async setApiKeyClientSecret(value: string, options?: StorageOptions): Promise<void> {
options = await this.getTimeoutBasedStorageOptions(options);
const account = await this.getAccount(options);
account.keys.apiKeyClientSecret = value;
await this.saveAccount(account, options);
}
async getAutoConfirmFingerPrints(options?: StorageOptions): Promise<boolean> {
return (
(await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions())))
@ -1356,7 +1321,10 @@ export class StateService<
}
async getIsAuthenticated(options?: StorageOptions): Promise<boolean> {
return (await this.getAccessToken(options)) != null && (await this.getUserId(options)) != null;
return (
(await this.tokenService.getAccessToken(options?.userId as UserId)) != null &&
(await this.getUserId(options)) != null
);
}
async getKdfConfig(options?: StorageOptions): Promise<KdfConfig> {
@ -1672,18 +1640,6 @@ export class StateService<
);
}
async getRefreshToken(options?: StorageOptions): Promise<string> {
options = await this.getTimeoutBasedStorageOptions(options);
return (await this.getAccount(options))?.tokens?.refreshToken;
}
async setRefreshToken(value: string, options?: StorageOptions): Promise<void> {
options = await this.getTimeoutBasedStorageOptions(options);
const account = await this.getAccount(options);
account.tokens.refreshToken = value;
await this.saveAccount(account, options);
}
async getRememberedEmail(options?: StorageOptions): Promise<string> {
return (
await this.getGlobals(this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()))
@ -1718,23 +1674,6 @@ export class StateService<
);
}
async getTwoFactorToken(options?: StorageOptions): Promise<string> {
return (
await this.getGlobals(this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()))
)?.twoFactorToken;
}
async setTwoFactorToken(value: string, options?: StorageOptions): Promise<void> {
const globals = await this.getGlobals(
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
);
globals.twoFactorToken = value;
await this.saveGlobals(
globals,
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
);
}
async getUserId(options?: StorageOptions): Promise<string> {
return (
await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions()))
@ -2041,15 +1980,6 @@ export class StateService<
await this.storageService.remove(keys.tempAccountSettings);
}
if (
account.settings.vaultTimeoutAction === VaultTimeoutAction.LogOut &&
account.settings.vaultTimeout != null
) {
account.tokens.accessToken = null;
account.tokens.refreshToken = null;
account.profile.apiKeyClientId = null;
account.keys.apiKeyClientSecret = null;
}
await this.saveAccount(
account,
this.reconcileOptions(
@ -2250,7 +2180,7 @@ export class StateService<
}
protected async deAuthenticateAccount(userId: string): Promise<void> {
await this.setAccessToken(null, { userId: userId });
await this.tokenService.clearAccessToken(userId as UserId);
await this.setLastActive(null, { userId: userId });
await this.updateState(async (state) => {
state.authenticatedAccounts = state.authenticatedAccounts.filter((id) => id !== userId);
@ -2293,16 +2223,6 @@ export class StateService<
return newActiveUser;
}
private async getTimeoutBasedStorageOptions(options?: StorageOptions): Promise<StorageOptions> {
const timeoutAction = await this.getVaultTimeoutAction({ userId: options?.userId });
const timeout = await this.getVaultTimeout({ userId: options?.userId });
const defaultOptions =
timeoutAction === VaultTimeoutAction.LogOut && timeout != null
? await this.defaultInMemoryOptions()
: await this.defaultOnDiskOptions();
return this.reconcileOptions(options, defaultOptions);
}
protected async saveSecureStorageKey<T extends JsonValue>(
key: string,
value: T,

View File

@ -28,6 +28,11 @@ export const PROVIDERS_DISK = new StateDefinition("providers", "disk");
export const ACCOUNT_MEMORY = new StateDefinition("account", "memory");
export const AVATAR_DISK = new StateDefinition("avatar", "disk", { web: "disk-local" });
export const SSO_DISK = new StateDefinition("ssoLogin", "disk");
export const TOKEN_DISK = new StateDefinition("token", "disk");
export const TOKEN_DISK_LOCAL = new StateDefinition("tokenDiskLocal", "disk", {
web: "disk-local",
});
export const TOKEN_MEMORY = new StateDefinition("token", "memory");
export const LOGIN_STRATEGY_MEMORY = new StateDefinition("loginStrategy", "memory");
// Autofill

View File

@ -93,6 +93,7 @@ import { SubscriptionResponse } from "../billing/models/response/subscription.re
import { TaxInfoResponse } from "../billing/models/response/tax-info.response";
import { TaxRateResponse } from "../billing/models/response/tax-rate.response";
import { DeviceType } from "../enums";
import { VaultTimeoutAction } from "../enums/vault-timeout-action.enum";
import { CollectionBulkDeleteRequest } from "../models/request/collection-bulk-delete.request";
import { DeleteRecoverRequest } from "../models/request/delete-recover.request";
import { EventRequest } from "../models/request/event.request";
@ -116,6 +117,7 @@ import { UserKeyResponse } from "../models/response/user-key.response";
import { AppIdService } from "../platform/abstractions/app-id.service";
import { EnvironmentService } from "../platform/abstractions/environment.service";
import { PlatformUtilsService } from "../platform/abstractions/platform-utils.service";
import { StateService } from "../platform/abstractions/state.service";
import { Utils } from "../platform/misc/utils";
import { AttachmentRequest } from "../vault/models/request/attachment.request";
import { CipherBulkDeleteRequest } from "../vault/models/request/cipher-bulk-delete.request";
@ -154,6 +156,7 @@ export class ApiService implements ApiServiceAbstraction {
private platformUtilsService: PlatformUtilsService,
private environmentService: EnvironmentService,
private appIdService: AppIdService,
private stateService: StateService,
private logoutCallback: (expired: boolean) => Promise<void>,
private customUserAgent: string = null,
) {
@ -224,7 +227,6 @@ export class ApiService implements ApiServiceAbstraction {
responseJson.TwoFactorProviders2 &&
Object.keys(responseJson.TwoFactorProviders2).length
) {
await this.tokenService.clearTwoFactorToken();
return new IdentityTwoFactorResponse(responseJson);
} else if (
response.status === 400 &&
@ -1578,10 +1580,10 @@ export class ApiService implements ApiServiceAbstraction {
// Helpers
async getActiveBearerToken(): Promise<string> {
let accessToken = await this.tokenService.getToken();
let accessToken = await this.tokenService.getAccessToken();
if (await this.tokenService.tokenNeedsRefresh()) {
await this.doAuthRefresh();
accessToken = await this.tokenService.getToken();
accessToken = await this.tokenService.getAccessToken();
}
return accessToken;
}
@ -1749,7 +1751,7 @@ export class ApiService implements ApiServiceAbstraction {
headers.set("User-Agent", this.customUserAgent);
}
const decodedToken = await this.tokenService.decodeToken();
const decodedToken = await this.tokenService.decodeAccessToken();
const response = await this.fetch(
new Request(this.environmentService.getIdentityUrl() + "/connect/token", {
body: this.qsStringify({
@ -1767,10 +1769,15 @@ export class ApiService implements ApiServiceAbstraction {
if (response.status === 200) {
const responseJson = await response.json();
const tokenResponse = new IdentityTokenResponse(responseJson);
const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction();
const vaultTimeout = await this.stateService.getVaultTimeout();
await this.tokenService.setTokens(
tokenResponse.accessToken,
tokenResponse.refreshToken,
null,
vaultTimeoutAction as VaultTimeoutAction,
vaultTimeout,
);
} else {
const error = await this.handleError(response, true, true);
@ -1796,7 +1803,14 @@ export class ApiService implements ApiServiceAbstraction {
throw new Error("Invalid response received when refreshing api token");
}
await this.tokenService.setToken(response.accessToken);
const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction();
const vaultTimeout = await this.stateService.getVaultTimeout();
await this.tokenService.setAccessToken(
response.accessToken,
vaultTimeoutAction as VaultTimeoutAction,
vaultTimeout,
);
}
async send(

View File

@ -29,7 +29,7 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA
async setVaultTimeoutOptions(timeout: number, action: VaultTimeoutAction): Promise<void> {
// We swap these tokens from being on disk for lock actions, and in memory for logout actions
// Get them here to set them to their new location after changing the timeout action and clearing if needed
const token = await this.tokenService.getToken();
const accessToken = await this.tokenService.getAccessToken();
const refreshToken = await this.tokenService.getRefreshToken();
const clientId = await this.tokenService.getClientId();
const clientSecret = await this.tokenService.getClientSecret();
@ -37,21 +37,22 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA
await this.stateService.setVaultTimeout(timeout);
const currentAction = await this.stateService.getVaultTimeoutAction();
if (
(timeout != null || timeout === 0) &&
action === VaultTimeoutAction.LogOut &&
action !== currentAction
) {
// if we have a vault timeout and the action is log out, reset tokens
await this.tokenService.clearToken();
await this.tokenService.clearTokens();
}
await this.stateService.setVaultTimeoutAction(action);
await this.tokenService.setToken(token);
await this.tokenService.setRefreshToken(refreshToken);
await this.tokenService.setClientId(clientId);
await this.tokenService.setClientSecret(clientSecret);
await this.tokenService.setTokens(accessToken, refreshToken, action, timeout, [
clientId,
clientSecret,
]);
await this.cryptoService.refreshAdditionalKeys();
}

View File

@ -24,7 +24,6 @@ import { RevertLastSyncMigrator } from "./migrations/26-revert-move-last-sync-to
import { BadgeSettingsMigrator } from "./migrations/27-move-badge-settings-to-state-providers";
import { MoveBiometricUnlockToStateProviders } from "./migrations/28-move-biometric-unlock-to-state-providers";
import { UserNotificationSettingsKeyMigrator } from "./migrations/29-move-user-notification-settings-to-state-provider";
import { FixPremiumMigrator } from "./migrations/3-fix-premium";
import { PolicyMigrator } from "./migrations/30-move-policy-state-to-state-provider";
import { EnableContextMenuMigrator } from "./migrations/31-move-enable-context-menu-to-autofill-settings-state-provider";
import { PreferredLanguageMigrator } from "./migrations/32-move-preferred-language";
@ -33,6 +32,7 @@ import { DomainSettingsMigrator } from "./migrations/34-move-domain-settings-to-
import { MoveThemeToStateProviderMigrator } from "./migrations/35-move-theme-to-state-providers";
import { VaultSettingsKeyMigrator } from "./migrations/36-move-show-card-and-identity-to-state-provider";
import { AvatarColorMigrator } from "./migrations/37-move-avatar-color-to-state-providers";
import { TokenServiceStateProviderMigrator } from "./migrations/38-migrate-token-svc-to-state-provider";
import { RemoveEverBeenUnlockedMigrator } from "./migrations/4-remove-ever-been-unlocked";
import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys";
import { RemoveLegacyEtmKeyMigrator } from "./migrations/6-remove-legacy-etm-key";
@ -41,14 +41,13 @@ import { MoveStateVersionMigrator } from "./migrations/8-move-state-version";
import { MoveBrowserSettingsToGlobal } from "./migrations/9-move-browser-settings-to-global";
import { MinVersionMigrator } from "./migrations/min-version";
export const MIN_VERSION = 2;
export const CURRENT_VERSION = 37;
export const MIN_VERSION = 3;
export const CURRENT_VERSION = 38;
export type MinVersion = typeof MIN_VERSION;
export function createMigrationBuilder() {
return MigrationBuilder.create()
.with(MinVersionMigrator)
.with(FixPremiumMigrator, 2, 3)
.with(RemoveEverBeenUnlockedMigrator, 3, 4)
.with(AddKeyTypeToOrgKeysMigrator, 4, 5)
.with(RemoveLegacyEtmKeyMigrator, 5, 6)
@ -82,7 +81,8 @@ export function createMigrationBuilder() {
.with(DomainSettingsMigrator, 33, 34)
.with(MoveThemeToStateProviderMigrator, 34, 35)
.with(VaultSettingsKeyMigrator, 35, 36)
.with(AvatarColorMigrator, 36, CURRENT_VERSION);
.with(AvatarColorMigrator, 36, 37)
.with(TokenServiceStateProviderMigrator, 37, CURRENT_VERSION);
}
export async function currentVersion(

View File

@ -1,111 +0,0 @@
import { MockProxy } from "jest-mock-extended";
// eslint-disable-next-line import/no-restricted-paths -- Used for testing migration, which requires import
import { TokenService } from "../../auth/services/token.service";
import { MigrationHelper } from "../migration-helper";
import { mockMigrationHelper } from "../migration-helper.spec";
import { FixPremiumMigrator } from "./3-fix-premium";
function migrateExampleJSON() {
return {
global: {
stateVersion: 2,
otherStuff: "otherStuff1",
},
authenticatedAccounts: [
"c493ed01-4e08-4e88-abc7-332f380ca760",
"23e61a5f-2ece-4f5e-b499-f0bc489482a9",
],
"c493ed01-4e08-4e88-abc7-332f380ca760": {
profile: {
otherStuff: "otherStuff2",
hasPremiumPersonally: null as boolean,
},
tokens: {
otherStuff: "otherStuff3",
accessToken: "accessToken",
},
otherStuff: "otherStuff4",
},
"23e61a5f-2ece-4f5e-b499-f0bc489482a9": {
profile: {
otherStuff: "otherStuff5",
hasPremiumPersonally: true,
},
tokens: {
otherStuff: "otherStuff6",
accessToken: "accessToken",
},
otherStuff: "otherStuff7",
},
otherStuff: "otherStuff8",
};
}
jest.mock("../../auth/services/token.service", () => ({
TokenService: {
decodeToken: jest.fn(),
},
}));
describe("FixPremiumMigrator", () => {
let helper: MockProxy<MigrationHelper>;
let sut: FixPremiumMigrator;
const decodeTokenSpy = TokenService.decodeToken as jest.Mock;
beforeEach(() => {
helper = mockMigrationHelper(migrateExampleJSON());
sut = new FixPremiumMigrator(2, 3);
});
afterEach(() => {
jest.resetAllMocks();
});
describe("migrate", () => {
it("should migrate hasPremiumPersonally", async () => {
decodeTokenSpy.mockResolvedValueOnce({ premium: true });
await sut.migrate(helper);
expect(helper.set).toHaveBeenCalledTimes(1);
expect(helper.set).toHaveBeenCalledWith("c493ed01-4e08-4e88-abc7-332f380ca760", {
profile: {
otherStuff: "otherStuff2",
hasPremiumPersonally: true,
},
tokens: {
otherStuff: "otherStuff3",
accessToken: "accessToken",
},
otherStuff: "otherStuff4",
});
});
it("should not migrate if decode throws", async () => {
decodeTokenSpy.mockRejectedValueOnce(new Error("test"));
await sut.migrate(helper);
expect(helper.set).not.toHaveBeenCalled();
});
it("should not migrate if decode returns null", async () => {
decodeTokenSpy.mockResolvedValueOnce(null);
await sut.migrate(helper);
expect(helper.set).not.toHaveBeenCalled();
});
});
describe("updateVersion", () => {
it("should update version", async () => {
await sut.updateVersion(helper, "up");
expect(helper.set).toHaveBeenCalledTimes(1);
expect(helper.set).toHaveBeenCalledWith("global", {
stateVersion: 3,
otherStuff: "otherStuff1",
});
});
});
});

View File

@ -1,48 +0,0 @@
// eslint-disable-next-line import/no-restricted-paths -- Used for token decoding, which are valid for days. We want the latest
import { TokenService } from "../../auth/services/token.service";
import { MigrationHelper } from "../migration-helper";
import { Migrator, IRREVERSIBLE, Direction } from "../migrator";
type ExpectedAccountType = {
profile?: { hasPremiumPersonally?: boolean };
tokens?: { accessToken?: string };
};
export class FixPremiumMigrator extends Migrator<2, 3> {
async migrate(helper: MigrationHelper): Promise<void> {
const accounts = await helper.getAccounts<ExpectedAccountType>();
async function fixPremium(userId: string, account: ExpectedAccountType) {
if (account?.profile?.hasPremiumPersonally === null && account.tokens?.accessToken != null) {
let decodedToken: { premium: boolean };
try {
decodedToken = await TokenService.decodeToken(account.tokens.accessToken);
} catch {
return;
}
if (decodedToken?.premium == null) {
return;
}
account.profile.hasPremiumPersonally = decodedToken?.premium;
return helper.set(userId, account);
}
}
await Promise.all(accounts.map(({ userId, account }) => fixPremium(userId, account)));
}
rollback(helper: MigrationHelper): Promise<void> {
throw IRREVERSIBLE;
}
// Override is necessary because default implementation assumes `stateVersion` at the root, but for this version
// it is nested inside a global object.
override async updateVersion(helper: MigrationHelper, direction: Direction): Promise<void> {
const endVersion = direction === "up" ? this.toVersion : this.fromVersion;
helper.currentVersion = endVersion;
const global: Record<string, unknown> = (await helper.get("global")) || {};
await helper.set("global", { ...global, stateVersion: endVersion });
}
}

View File

@ -0,0 +1,258 @@
import { MockProxy, any } from "jest-mock-extended";
import { MigrationHelper } from "../migration-helper";
import { mockMigrationHelper } from "../migration-helper.spec";
import {
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
ACCESS_TOKEN_DISK,
REFRESH_TOKEN_DISK,
API_KEY_CLIENT_ID_DISK,
API_KEY_CLIENT_SECRET_DISK,
TokenServiceStateProviderMigrator,
} from "./38-migrate-token-svc-to-state-provider";
// Represents data in state service pre-migration
function preMigrationJson() {
return {
global: {
twoFactorToken: "twoFactorToken",
otherStuff: "otherStuff1",
},
authenticatedAccounts: ["user1", "user2", "user3"],
user1: {
tokens: {
accessToken: "accessToken",
refreshToken: "refreshToken",
otherStuff: "overStuff2",
},
profile: {
apiKeyClientId: "apiKeyClientId",
email: "user1Email",
otherStuff: "overStuff3",
},
keys: {
apiKeyClientSecret: "apiKeyClientSecret",
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
},
user2: {
tokens: {
// no tokens to migrate
otherStuff: "overStuff2",
},
profile: {
// no apiKeyClientId to migrate
otherStuff: "overStuff3",
email: "user2Email",
},
keys: {
// no apiKeyClientSecret to migrate
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
},
};
}
function rollbackJSON() {
return {
// User specific state provider data
// use pattern user_{userId}_{stateDefinitionName}_{keyDefinitionKey} for user data
// User1 migrated data
user_user1_token_accessToken: "accessToken",
user_user1_token_refreshToken: "refreshToken",
user_user1_token_apiKeyClientId: "apiKeyClientId",
user_user1_token_apiKeyClientSecret: "apiKeyClientSecret",
// User2 migrated data
user_user2_token_accessToken: null as any,
user_user2_token_refreshToken: null as any,
user_user2_token_apiKeyClientId: null as any,
user_user2_token_apiKeyClientSecret: null as any,
// Global state provider data
// use pattern global_{stateDefinitionName}_{keyDefinitionKey} for global data
global_tokenDiskLocal_emailTwoFactorTokenRecord: {
user1Email: "twoFactorToken",
user2Email: "twoFactorToken",
},
global: {
// no longer has twoFactorToken
otherStuff: "otherStuff1",
},
authenticatedAccounts: ["user1", "user2", "user3"],
user1: {
tokens: {
otherStuff: "overStuff2",
},
profile: {
email: "user1Email",
otherStuff: "overStuff3",
},
keys: {
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
},
user2: {
tokens: {
otherStuff: "overStuff2",
},
profile: {
email: "user2Email",
otherStuff: "overStuff3",
},
keys: {
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
},
};
}
describe("TokenServiceStateProviderMigrator", () => {
let helper: MockProxy<MigrationHelper>;
let sut: TokenServiceStateProviderMigrator;
describe("migrate", () => {
beforeEach(() => {
helper = mockMigrationHelper(preMigrationJson(), 37);
sut = new TokenServiceStateProviderMigrator(37, 38);
});
it("should remove state service data from all accounts that have it", async () => {
await sut.migrate(helper);
expect(helper.set).toHaveBeenCalledWith("user1", {
tokens: {
otherStuff: "overStuff2",
},
profile: {
email: "user1Email",
otherStuff: "overStuff3",
},
keys: {
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
});
expect(helper.set).toHaveBeenCalledTimes(2);
expect(helper.set).not.toHaveBeenCalledWith("user2", any());
expect(helper.set).not.toHaveBeenCalledWith("user3", any());
});
it("should migrate data to state providers for defined accounts that have the data", async () => {
await sut.migrate(helper);
// Two factor Token Migration
expect(helper.setToGlobal).toHaveBeenLastCalledWith(
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
{
user1Email: "twoFactorToken",
user2Email: "twoFactorToken",
},
);
expect(helper.setToGlobal).toHaveBeenCalledTimes(1);
expect(helper.setToUser).toHaveBeenCalledWith("user1", ACCESS_TOKEN_DISK, "accessToken");
expect(helper.setToUser).toHaveBeenCalledWith("user1", REFRESH_TOKEN_DISK, "refreshToken");
expect(helper.setToUser).toHaveBeenCalledWith(
"user1",
API_KEY_CLIENT_ID_DISK,
"apiKeyClientId",
);
expect(helper.setToUser).toHaveBeenCalledWith(
"user1",
API_KEY_CLIENT_SECRET_DISK,
"apiKeyClientSecret",
);
expect(helper.setToUser).not.toHaveBeenCalledWith("user2", ACCESS_TOKEN_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user2", REFRESH_TOKEN_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user2", API_KEY_CLIENT_ID_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user2", API_KEY_CLIENT_SECRET_DISK, any());
// Expect that we didn't migrate anything to user 3
expect(helper.setToUser).not.toHaveBeenCalledWith("user3", ACCESS_TOKEN_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user3", REFRESH_TOKEN_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user3", API_KEY_CLIENT_ID_DISK, any());
expect(helper.setToUser).not.toHaveBeenCalledWith("user3", API_KEY_CLIENT_SECRET_DISK, any());
});
});
describe("rollback", () => {
beforeEach(() => {
helper = mockMigrationHelper(rollbackJSON(), 38);
sut = new TokenServiceStateProviderMigrator(37, 38);
});
it("should null out newly migrated entries in state provider framework", async () => {
await sut.rollback(helper);
expect(helper.setToGlobal).toHaveBeenCalledWith(
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
null,
);
expect(helper.setToUser).toHaveBeenCalledWith("user1", ACCESS_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user1", REFRESH_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user1", API_KEY_CLIENT_ID_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user1", API_KEY_CLIENT_SECRET_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user2", ACCESS_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user2", REFRESH_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user2", API_KEY_CLIENT_ID_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user2", API_KEY_CLIENT_SECRET_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user3", ACCESS_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user3", REFRESH_TOKEN_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user3", API_KEY_CLIENT_ID_DISK, null);
expect(helper.setToUser).toHaveBeenCalledWith("user3", API_KEY_CLIENT_SECRET_DISK, null);
});
it("should add back data to all accounts that had migrated data (only user 1)", async () => {
await sut.rollback(helper);
expect(helper.set).toHaveBeenCalledWith("user1", {
tokens: {
accessToken: "accessToken",
refreshToken: "refreshToken",
otherStuff: "overStuff2",
},
profile: {
apiKeyClientId: "apiKeyClientId",
email: "user1Email",
otherStuff: "overStuff3",
},
keys: {
apiKeyClientSecret: "apiKeyClientSecret",
otherStuff: "overStuff4",
},
otherStuff: "otherStuff5",
});
});
it("should add back the global twoFactorToken", async () => {
await sut.rollback(helper);
expect(helper.set).toHaveBeenCalledWith("global", {
twoFactorToken: "twoFactorToken",
otherStuff: "otherStuff1",
});
});
it("should not add data back if data wasn't migrated or acct doesn't exist", async () => {
await sut.rollback(helper);
// no data to add back for user2 (acct exists but no migrated data) and user3 (no acct)
expect(helper.set).not.toHaveBeenCalledWith("user2", any());
expect(helper.set).not.toHaveBeenCalledWith("user3", any());
});
});
});

View File

@ -0,0 +1,231 @@
import { KeyDefinitionLike, MigrationHelper, StateDefinitionLike } from "../migration-helper";
import { Migrator } from "../migrator";
// Types to represent data as it is stored in JSON
type ExpectedAccountType = {
tokens?: {
accessToken?: string;
refreshToken?: string;
};
profile?: {
apiKeyClientId?: string;
email?: string;
};
keys?: {
apiKeyClientSecret?: string;
};
};
type ExpectedGlobalType = {
twoFactorToken?: string;
};
export const EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL: KeyDefinitionLike = {
key: "emailTwoFactorTokenRecord",
stateDefinition: {
name: "tokenDiskLocal",
},
};
const TOKEN_STATE_DEF_LIKE: StateDefinitionLike = {
name: "token",
};
export const ACCESS_TOKEN_DISK: KeyDefinitionLike = {
key: "accessToken", // matches KeyDefinition.key
stateDefinition: TOKEN_STATE_DEF_LIKE,
};
export const REFRESH_TOKEN_DISK: KeyDefinitionLike = {
key: "refreshToken",
stateDefinition: TOKEN_STATE_DEF_LIKE,
};
export const API_KEY_CLIENT_ID_DISK: KeyDefinitionLike = {
key: "apiKeyClientId",
stateDefinition: TOKEN_STATE_DEF_LIKE,
};
export const API_KEY_CLIENT_SECRET_DISK: KeyDefinitionLike = {
key: "apiKeyClientSecret",
stateDefinition: TOKEN_STATE_DEF_LIKE,
};
export class TokenServiceStateProviderMigrator extends Migrator<37, 38> {
async migrate(helper: MigrationHelper): Promise<void> {
// Move global data
const globalData = await helper.get<ExpectedGlobalType>("global");
// Create new global record for 2FA token that we can accumulate data in
const emailTwoFactorTokenRecord = {};
const accounts = await helper.getAccounts<ExpectedAccountType>();
async function migrateAccount(
userId: string,
account: ExpectedAccountType | undefined,
globalTwoFactorToken: string | undefined,
emailTwoFactorTokenRecord: Record<string, string>,
): Promise<void> {
let updatedAccount = false;
// migrate 2FA token from global to user state
// Due to the existing implmentation, n users on the same device share the same global state value for 2FA token.
// So, we will just migrate it to all users to keep it valid for whichever was the user that set it previously.
// Note: don't bother migrating 2FA Token if user account or email is undefined
const email = account?.profile?.email;
if (globalTwoFactorToken != undefined && account != undefined && email != undefined) {
emailTwoFactorTokenRecord[email] = globalTwoFactorToken;
// Note: don't set updatedAccount to true here as we aren't updating
// the legacy user state, just migrating a global state to a new user state
}
// Migrate access token
const existingAccessToken = account?.tokens?.accessToken;
if (existingAccessToken != null) {
// Only migrate data that exists
await helper.setToUser(userId, ACCESS_TOKEN_DISK, existingAccessToken);
delete account.tokens.accessToken;
updatedAccount = true;
}
// Migrate refresh token
const existingRefreshToken = account?.tokens?.refreshToken;
if (existingRefreshToken != null) {
await helper.setToUser(userId, REFRESH_TOKEN_DISK, existingRefreshToken);
delete account.tokens.refreshToken;
updatedAccount = true;
}
// Migrate API key client id
const existingApiKeyClientId = account?.profile?.apiKeyClientId;
if (existingApiKeyClientId != null) {
await helper.setToUser(userId, API_KEY_CLIENT_ID_DISK, existingApiKeyClientId);
delete account.profile.apiKeyClientId;
updatedAccount = true;
}
// Migrate API key client secret
const existingApiKeyClientSecret = account?.keys?.apiKeyClientSecret;
if (existingApiKeyClientSecret != null) {
await helper.setToUser(userId, API_KEY_CLIENT_SECRET_DISK, existingApiKeyClientSecret);
delete account.keys.apiKeyClientSecret;
updatedAccount = true;
}
if (updatedAccount) {
// Save the migrated account only if it was updated
await helper.set(userId, account);
}
}
await Promise.all([
...accounts.map(({ userId, account }) =>
migrateAccount(userId, account, globalData?.twoFactorToken, emailTwoFactorTokenRecord),
),
]);
// Save the global 2FA token record
await helper.setToGlobal(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, emailTwoFactorTokenRecord);
// Delete global data
delete globalData?.twoFactorToken;
await helper.set("global", globalData);
}
async rollback(helper: MigrationHelper): Promise<void> {
const accounts = await helper.getAccounts<ExpectedAccountType>();
// Since we migrated the global 2FA token to all users, we need to rollback the 2FA token for all users
// but we only need to set it to the global state once
// Go through accounts and find the first user that has a non-null email and 2FA token
let migratedTwoFactorToken: string | null = null;
for (const { account } of accounts) {
const email = account?.profile?.email;
if (email == null) {
continue;
}
const emailTwoFactorTokenRecord: Record<string, string> = await helper.getFromGlobal(
EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL,
);
migratedTwoFactorToken = emailTwoFactorTokenRecord[email];
if (migratedTwoFactorToken != null) {
break;
}
}
if (migratedTwoFactorToken != null) {
let legacyGlobal = await helper.get<ExpectedGlobalType>("global");
if (!legacyGlobal) {
legacyGlobal = {};
}
legacyGlobal.twoFactorToken = migratedTwoFactorToken;
await helper.set("global", legacyGlobal);
}
// delete global 2FA token record
await helper.setToGlobal(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, null);
async function rollbackAccount(userId: string, account: ExpectedAccountType): Promise<void> {
let updatedLegacyAccount = false;
// Rollback access token
const migratedAccessToken = await helper.getFromUser<string>(userId, ACCESS_TOKEN_DISK);
if (account?.tokens && migratedAccessToken != null) {
account.tokens.accessToken = migratedAccessToken;
updatedLegacyAccount = true;
}
await helper.setToUser(userId, ACCESS_TOKEN_DISK, null);
// Rollback refresh token
const migratedRefreshToken = await helper.getFromUser<string>(userId, REFRESH_TOKEN_DISK);
if (account?.tokens && migratedRefreshToken != null) {
account.tokens.refreshToken = migratedRefreshToken;
updatedLegacyAccount = true;
}
await helper.setToUser(userId, REFRESH_TOKEN_DISK, null);
// Rollback API key client id
const migratedApiKeyClientId = await helper.getFromUser<string>(
userId,
API_KEY_CLIENT_ID_DISK,
);
if (account?.profile && migratedApiKeyClientId != null) {
account.profile.apiKeyClientId = migratedApiKeyClientId;
updatedLegacyAccount = true;
}
await helper.setToUser(userId, API_KEY_CLIENT_ID_DISK, null);
// Rollback API key client secret
const migratedApiKeyClientSecret = await helper.getFromUser<string>(
userId,
API_KEY_CLIENT_SECRET_DISK,
);
if (account?.keys && migratedApiKeyClientSecret != null) {
account.keys.apiKeyClientSecret = migratedApiKeyClientSecret;
updatedLegacyAccount = true;
}
await helper.setToUser(userId, API_KEY_CLIENT_SECRET_DISK, null);
if (updatedLegacyAccount) {
await helper.set(userId, account);
}
}
await Promise.all([...accounts.map(({ userId, account }) => rollbackAccount(userId, account))]);
}
}

View File

@ -2,7 +2,6 @@ import { Injectable, NgZone } from "@angular/core";
import { OidcClient } from "oidc-client-ts";
import { Subject, firstValueFrom } from "rxjs";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { ClientType } from "@bitwarden/common/enums";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service";
@ -32,7 +31,6 @@ export class LastPassDirectImportService {
ssoImportCallback$ = this._ssoImportCallback$.asObservable();
constructor(
private tokenService: TokenService,
private cryptoFunctionService: CryptoFunctionService,
private environmentService: EnvironmentService,
private appIdService: AppIdService,
@ -44,7 +42,7 @@ export class LastPassDirectImportService {
private dialogService: DialogService,
private i18nService: I18nService,
) {
this.vault = new Vault(this.cryptoFunctionService, this.tokenService);
this.vault = new Vault(this.cryptoFunctionService);
/** TODO: remove this in favor of dedicated service */
this.broadcasterService.subscribe("LastPassDirectImportService", (message: any) => {

View File

@ -1,6 +1,6 @@
import * as papa from "papaparse";
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
import { decodeJwtTokenToJson } from "@bitwarden/auth/common";
import { HttpStatusCode } from "@bitwarden/common/enums";
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
@ -24,10 +24,7 @@ export class Vault {
private client: Client;
private cryptoUtils: CryptoUtils;
constructor(
private cryptoFunctionService: CryptoFunctionService,
private tokenService: TokenService,
) {
constructor(private cryptoFunctionService: CryptoFunctionService) {
this.cryptoUtils = new CryptoUtils(cryptoFunctionService);
const parser = new Parser(cryptoFunctionService, this.cryptoUtils);
this.client = new Client(parser, this.cryptoUtils);
@ -212,7 +209,7 @@ export class Vault {
}
private async getK1FromAccessToken(federatedUser: FederatedUserContext, b64: boolean) {
const decodedAccessToken = await this.tokenService.decodeToken(federatedUser.accessToken);
const decodedAccessToken = decodeJwtTokenToJson(federatedUser.accessToken);
const k1 = decodedAccessToken?.LastPassK1 as string;
if (k1 != null) {
return b64 ? Utils.fromB64ToArray(k1) : Utils.fromByteStringToArray(k1);