diff --git a/libs/common/src/platform/abstractions/state.service.ts b/libs/common/src/platform/abstractions/state.service.ts index b6300239028..b59c69a92ff 100644 --- a/libs/common/src/platform/abstractions/state.service.ts +++ b/libs/common/src/platform/abstractions/state.service.ts @@ -225,8 +225,6 @@ export abstract class StateService { * @deprecated Do not call this, use PolicyService */ setDecryptedPolicies: (value: Policy[], options?: StorageOptions) => Promise; - getDecryptedPrivateKey: (options?: StorageOptions) => Promise; - setDecryptedPrivateKey: (value: Uint8Array, options?: StorageOptions) => Promise; /** * @deprecated Do not call this directly, use SendService */ @@ -346,8 +344,6 @@ export abstract class StateService { value: { [id: string]: PolicyData }, options?: StorageOptions, ) => Promise; - getEncryptedPrivateKey: (options?: StorageOptions) => Promise; - setEncryptedPrivateKey: (value: string, options?: StorageOptions) => Promise; /** * @deprecated Do not call this directly, use SendService */ @@ -434,8 +430,6 @@ export abstract class StateService { setProtectedPin: (value: string, options?: StorageOptions) => Promise; getProviders: (options?: StorageOptions) => Promise<{ [id: string]: ProviderData }>; setProviders: (value: { [id: string]: ProviderData }, options?: StorageOptions) => Promise; - getPublicKey: (options?: StorageOptions) => Promise; - setPublicKey: (value: Uint8Array, options?: StorageOptions) => Promise; getRefreshToken: (options?: StorageOptions) => Promise; setRefreshToken: (value: string, options?: StorageOptions) => Promise; getRememberedEmail: (options?: StorageOptions) => Promise; diff --git a/libs/common/src/platform/models/domain/account.ts b/libs/common/src/platform/models/domain/account.ts index d3a7da45dac..fc2350941d7 100644 --- a/libs/common/src/platform/models/domain/account.ts +++ b/libs/common/src/platform/models/domain/account.ts @@ -125,7 +125,6 @@ export class AccountKeys { masterKey?: MasterKey; masterKeyEncryptedUserKey?: string; deviceKey?: ReturnType; - privateKey?: EncryptionPair = new EncryptionPair(); publicKey?: Uint8Array; apiKeyClientSecret?: string; @@ -163,9 +162,6 @@ export class AccountKeys { obj?.cryptoSymmetricKey, SymmetricCryptoKey.fromJSON, ), - privateKey: EncryptionPair.fromJSON(obj?.privateKey, (decObj: string) => - Utils.fromByteStringToArray(decObj), - ), publicKey: Utils.fromByteStringToArray(obj?.publicKey), }); } diff --git a/libs/common/src/platform/services/crypto.service.ts b/libs/common/src/platform/services/crypto.service.ts index 47c6dd791e9..2991b6e57a9 100644 --- a/libs/common/src/platform/services/crypto.service.ts +++ b/libs/common/src/platform/services/crypto.service.ts @@ -9,7 +9,16 @@ import { AccountService } from "../../auth/abstractions/account.service"; import { KdfConfig } from "../../auth/models/domain/kdf-config"; import { Utils } from "../../platform/misc/utils"; import { OrganizationId, ProviderId, UserId } from "../../types/guid"; -import { OrgKey, UserKey, MasterKey, ProviderKey, PinKey, CipherKey } from "../../types/key"; +import { + OrgKey, + UserKey, + MasterKey, + ProviderKey, + PinKey, + CipherKey, + UserPrivateKey, + UserPublicKey, +} from "../../types/key"; import { CryptoFunctionService } from "../abstractions/crypto-function.service"; import { CryptoService as CryptoServiceAbstraction } from "../abstractions/crypto.service"; import { EncryptService } from "../abstractions/encrypt.service"; @@ -38,7 +47,12 @@ import { USER_ORGANIZATION_KEYS, } from "./key-state/org-keys.state"; import { USER_ENCRYPTED_PROVIDER_KEYS, USER_PROVIDER_KEYS } from "./key-state/provider-keys.state"; -import { USER_EVER_HAD_USER_KEY } from "./key-state/user-key.state"; +import { + USER_ENCRYPTED_PRIVATE_KEY, + USER_EVER_HAD_USER_KEY, + USER_PRIVATE_KEY, + USER_PUBLIC_KEY, +} from "./key-state/user-key.state"; export class CryptoService implements CryptoServiceAbstraction { private readonly activeUserEverHadUserKey: ActiveUserState; @@ -49,12 +63,16 @@ export class CryptoService implements CryptoServiceAbstraction { private readonly activeUserEncryptedProviderKeysState: ActiveUserState< Record >; - private readonly activeUserProviderKeysState: DerivedState>; + private readonly activeUserProviderKeysState: DerivedState>; + private readonly activeUserEncryptedPrivateKeyState: ActiveUserState; + private readonly activeUserPrivateKeyState: DerivedState; + private readonly activeUserPublicKeyState: DerivedState; readonly activeUserOrgKeys$: Observable>; readonly activeUserProviderKeys$: Observable>; - - readonly everHadUserKey$; + readonly activeUserPrivateKey$: Observable; + readonly activeUserPublicKey$: Observable; + readonly everHadUserKey$: Observable; constructor( protected cryptoFunctionService: CryptoFunctionService, @@ -65,7 +83,31 @@ export class CryptoService implements CryptoServiceAbstraction { protected accountService: AccountService, protected stateProvider: StateProvider, ) { + // User Key this.activeUserEverHadUserKey = stateProvider.getActive(USER_EVER_HAD_USER_KEY); + this.everHadUserKey$ = this.activeUserEverHadUserKey.state$.pipe(map((x) => x ?? false)); + + // User Asymmetric Key Pair + this.activeUserEncryptedPrivateKeyState = stateProvider.getActive(USER_ENCRYPTED_PRIVATE_KEY); + this.activeUserPrivateKeyState = stateProvider.getDerived( + this.activeUserEncryptedPrivateKeyState.combinedState$, + USER_PRIVATE_KEY, + { + encryptService: this.encryptService, + cryptoService: this, + }, + ); + this.activeUserPrivateKey$ = this.activeUserPrivateKeyState.state$; // may be null + this.activeUserPublicKeyState = stateProvider.getDerived( + this.activeUserPrivateKey$, + USER_PUBLIC_KEY, + { + cryptoFunctionService: this.cryptoFunctionService, + }, + ); + this.activeUserPublicKey$ = this.activeUserPublicKeyState.state$; // may be null + + // Organization keys this.activeUserEncryptedOrgKeysState = stateProvider.getActive( USER_ENCRYPTED_ORGANIZATION_KEYS, ); @@ -74,6 +116,9 @@ export class CryptoService implements CryptoServiceAbstraction { USER_ORGANIZATION_KEYS, { cryptoService: this }, ); + this.activeUserOrgKeys$ = this.activeUserOrgKeysState.state$; // null handled by `derive` function + + // Provider keys this.activeUserEncryptedProviderKeysState = stateProvider.getActive( USER_ENCRYPTED_PROVIDER_KEYS, ); @@ -82,9 +127,6 @@ export class CryptoService implements CryptoServiceAbstraction { USER_PROVIDER_KEYS, { encryptService: this.encryptService, cryptoService: this }, ); - - this.everHadUserKey$ = this.activeUserEverHadUserKey.state$.pipe(map((x) => x ?? false)); - this.activeUserOrgKeys$ = this.activeUserOrgKeysState.state$; // null handled by `derive` function this.activeUserProviderKeys$ = this.activeUserProviderKeysState.state$; // null handled by `derive` function } @@ -465,19 +507,7 @@ export class CryptoService implements CryptoServiceAbstraction { } async getPublicKey(): Promise { - const inMemoryPublicKey = await this.stateService.getPublicKey(); - if (inMemoryPublicKey != null) { - return inMemoryPublicKey; - } - - const privateKey = await this.getPrivateKey(); - if (privateKey == null) { - return null; - } - - const publicKey = await this.cryptoFunctionService.rsaExtractPublicKey(privateKey); - await this.stateService.setPublicKey(publicKey); - return publicKey; + return await firstValueFrom(this.activeUserPublicKey$); } async makeOrgKey(): Promise<[EncString, T]> { @@ -487,32 +517,16 @@ export class CryptoService implements CryptoServiceAbstraction { return [encShareKey, new SymmetricCryptoKey(shareKey) as T]; } - async setPrivateKey(encPrivateKey: string): Promise { + async setPrivateKey(encPrivateKey: EncryptedString): Promise { if (encPrivateKey == null) { return; } - await this.stateService.setDecryptedPrivateKey(null); - await this.stateService.setEncryptedPrivateKey(encPrivateKey); + await this.activeUserEncryptedPrivateKeyState.update(() => encPrivateKey); } async getPrivateKey(): Promise { - const decryptedPrivateKey = await this.stateService.getDecryptedPrivateKey(); - if (decryptedPrivateKey != null) { - return decryptedPrivateKey; - } - - const encPrivateKey = await this.stateService.getEncryptedPrivateKey(); - if (encPrivateKey == null) { - return null; - } - - const privateKey = await this.encryptService.decryptToBytes( - new EncString(encPrivateKey), - await this.getUserKeyWithLegacySupport(), - ); - await this.stateService.setDecryptedPrivateKey(privateKey); - return privateKey; + return await firstValueFrom(this.activeUserPrivateKey$); } async getFingerprint(fingerprintMaterial: string, publicKey?: Uint8Array): Promise { @@ -543,14 +557,23 @@ export class CryptoService implements CryptoServiceAbstraction { } async clearKeyPair(memoryOnly?: boolean, userId?: UserId): Promise { - const keysToClear: Promise[] = [ - this.stateService.setDecryptedPrivateKey(null, { userId: userId }), - this.stateService.setPublicKey(null, { userId: userId }), - ]; - if (!memoryOnly) { - keysToClear.push(this.stateService.setEncryptedPrivateKey(null, { userId: userId })); + const activeUserId = (await firstValueFrom(this.accountService.activeAccount$))?.id; + const userIdIsActive = userId == null || userId === activeUserId; + if (memoryOnly && userIdIsActive) { + // key pair is only cached for active users + await this.activeUserPrivateKeyState.forceValue(null); + await this.activeUserPublicKeyState.forceValue(null); + return; + } else { + if (userId == null && activeUserId == null) { + // nothing to do + return; + } + // below updates decrypted private key and public keys if this is the active user as well since those are derived from the encrypted private key + await this.stateProvider + .getUser(userId ?? activeUserId, USER_ENCRYPTED_PRIVATE_KEY) + .update(() => null); } - return Promise.all(keysToClear); } async makePinKey(pin: string, salt: string, kdf: KdfType, kdfConfig: KdfConfig): Promise { @@ -735,16 +758,23 @@ export class CryptoService implements CryptoServiceAbstraction { } try { - const encPrivateKey = await this.stateService.getEncryptedPrivateKey(); + const [userId, encPrivateKey] = await firstValueFrom( + this.activeUserEncryptedPrivateKeyState.combinedState$, + ); if (encPrivateKey == null) { return false; } - const privateKey = await this.encryptService.decryptToBytes( - new EncString(encPrivateKey), - key, - ); - await this.cryptoFunctionService.rsaExtractPublicKey(privateKey); + // Can decrypt private key + const privateKey = await USER_PRIVATE_KEY.derive([userId, encPrivateKey], { + encryptService: this.encryptService, + cryptoService: this, + }); + + // Can successfully derive public key + await USER_PUBLIC_KEY.derive(privateKey, { + cryptoFunctionService: this.cryptoFunctionService, + }); } catch (e) { return false; } @@ -765,7 +795,7 @@ export class CryptoService implements CryptoServiceAbstraction { const userKey = new SymmetricCryptoKey(rawKey) as UserKey; const [publicKey, privateKey] = await this.makeKeyPair(userKey); await this.setUserKey(userKey); - await this.stateService.setEncryptedPrivateKey(privateKey.encryptedString); + await this.activeUserEncryptedPrivateKeyState.update(() => privateKey.encryptedString); return { userKey, diff --git a/libs/common/src/platform/services/key-state/user-key.state.spec.ts b/libs/common/src/platform/services/key-state/user-key.state.spec.ts new file mode 100644 index 00000000000..cb758943e51 --- /dev/null +++ b/libs/common/src/platform/services/key-state/user-key.state.spec.ts @@ -0,0 +1,130 @@ +import { mock } from "jest-mock-extended"; + +import { makeStaticByteArray } from "../../../../spec"; +import { UserId } from "../../../types/guid"; +import { UserKey, UserPrivateKey, UserPublicKey } from "../../../types/key"; +import { CryptoFunctionService } from "../../abstractions/crypto-function.service"; +import { EncryptService } from "../../abstractions/encrypt.service"; +import { EncryptionType } from "../../enums"; +import { Utils } from "../../misc/utils"; +import { EncString } from "../../models/domain/enc-string"; +import { CryptoService } from "../crypto.service"; + +import { + USER_ENCRYPTED_PRIVATE_KEY, + USER_EVER_HAD_USER_KEY, + USER_PRIVATE_KEY, + USER_PUBLIC_KEY, +} from "./user-key.state"; + +function makeEncString(data?: string) { + data ??= Utils.newGuid(); + return new EncString(EncryptionType.AesCbc256_HmacSha256_B64, data, "test", "test"); +} + +describe("Ever had user key", () => { + const sut = USER_EVER_HAD_USER_KEY; + + it("should deserialize ever had user key", () => { + const everHadUserKey = true; + + const result = sut.deserializer(JSON.parse(JSON.stringify(everHadUserKey))); + + expect(result).toEqual(everHadUserKey); + }); +}); + +describe("Encrypted private key", () => { + const sut = USER_ENCRYPTED_PRIVATE_KEY; + + it("should deserialize encrypted private key", () => { + const encryptedPrivateKey = makeEncString().encryptedString; + + const result = sut.deserializer(JSON.parse(JSON.stringify(encryptedPrivateKey))); + + expect(result).toEqual(encryptedPrivateKey); + }); +}); + +describe("User public key", () => { + const sut = USER_PUBLIC_KEY; + const userPrivateKey = makeStaticByteArray(64, 1) as UserPrivateKey; + const userPublicKey = makeStaticByteArray(64, 2) as UserPublicKey; + + it("should deserialize user public key", () => { + const userPublicKey = makeStaticByteArray(64, 1); + + const result = sut.deserialize(JSON.parse(JSON.stringify(userPublicKey))); + + expect(result).toEqual(userPublicKey); + }); + + it("should derive user public key", async () => { + const cryptoFunctionService = mock(); + cryptoFunctionService.rsaExtractPublicKey.mockResolvedValue(userPublicKey); + + const result = await sut.derive(userPrivateKey, { cryptoFunctionService }); + + expect(result).toEqual(userPublicKey); + }); +}); + +describe("Derived decrypted private key", () => { + const sut = USER_PRIVATE_KEY; + const userId = "userId" as UserId; + const userKey = mock(); + const encryptedPrivateKey = makeEncString().encryptedString; + const decryptedPrivateKey = makeStaticByteArray(64, 1); + + afterEach(() => { + jest.resetAllMocks(); + }); + + it("should deserialize decrypted private key", () => { + const decryptedPrivateKey = makeStaticByteArray(64, 1); + + const result = sut.deserialize(JSON.parse(JSON.stringify(decryptedPrivateKey))); + + expect(result).toEqual(decryptedPrivateKey); + }); + + it("should derive decrypted private key", async () => { + const cryptoService = mock(); + cryptoService.getUserKey.mockResolvedValue(userKey); + const encryptService = mock(); + encryptService.decryptToBytes.mockResolvedValue(decryptedPrivateKey); + + const result = await sut.derive([userId, encryptedPrivateKey], { + encryptService, + cryptoService, + }); + + expect(result).toEqual(decryptedPrivateKey); + }); + + it("should handle null input values", async () => { + const cryptoService = mock(); + cryptoService.getUserKey.mockResolvedValue(userKey); + const encryptService = mock(); + + const result = await sut.derive([userId, null], { + encryptService, + cryptoService, + }); + + expect(result).toEqual(null); + }); + + it("should handle null user key", async () => { + const cryptoService = mock(); + cryptoService.getUserKey.mockResolvedValue(null); + const encryptService = mock(); + + const result = await sut.derive([userId, encryptedPrivateKey], { + encryptService, + cryptoService, + }); + + expect(result).toEqual(null); + }); +}); diff --git a/libs/common/src/platform/services/key-state/user-key.state.ts b/libs/common/src/platform/services/key-state/user-key.state.ts index fb192d7ac36..a6d1619e945 100644 --- a/libs/common/src/platform/services/key-state/user-key.state.ts +++ b/libs/common/src/platform/services/key-state/user-key.state.ts @@ -1,5 +1,59 @@ -import { KeyDefinition, CRYPTO_DISK } from "../../state"; +import { UserPrivateKey, UserPublicKey } from "../../../types/key"; +import { CryptoFunctionService } from "../../abstractions/crypto-function.service"; +import { EncryptService } from "../../abstractions/encrypt.service"; +import { EncString, EncryptedString } from "../../models/domain/enc-string"; +import { KeyDefinition, CRYPTO_DISK, DeriveDefinition } from "../../state"; +import { CryptoService } from "../crypto.service"; export const USER_EVER_HAD_USER_KEY = new KeyDefinition(CRYPTO_DISK, "everHadUserKey", { deserializer: (obj) => obj, }); + +export const USER_ENCRYPTED_PRIVATE_KEY = new KeyDefinition( + CRYPTO_DISK, + "privateKey", + { + deserializer: (obj) => obj, + }, +); + +export const USER_PRIVATE_KEY = DeriveDefinition.fromWithUserId< + EncryptedString, + UserPrivateKey, + // TODO: update cryptoService to user key directly + { encryptService: EncryptService; cryptoService: CryptoService } +>(USER_ENCRYPTED_PRIVATE_KEY, { + deserializer: (obj) => new Uint8Array(Object.values(obj)) as UserPrivateKey, + derive: async ([userId, encPrivateKeyString], { encryptService, cryptoService }) => { + if (encPrivateKeyString == null) { + return null; + } + + const userKey = await cryptoService.getUserKey(userId); + if (userKey == null) { + return null; + } + + const encPrivateKey = new EncString(encPrivateKeyString); + const privateKey = (await encryptService.decryptToBytes( + encPrivateKey, + userKey, + )) as UserPrivateKey; + return privateKey; + }, +}); + +export const USER_PUBLIC_KEY = DeriveDefinition.from< + UserPrivateKey, + UserPublicKey, + { cryptoFunctionService: CryptoFunctionService } +>([USER_PRIVATE_KEY, "publicKey"], { + deserializer: (obj) => new Uint8Array(Object.values(obj)) as UserPublicKey, + derive: async (privateKey, { cryptoFunctionService }) => { + if (privateKey == null) { + return null; + } + + return (await cryptoFunctionService.rsaExtractPublicKey(privateKey)) as UserPublicKey; + }, +}); diff --git a/libs/common/src/platform/services/state.service.ts b/libs/common/src/platform/services/state.service.ts index 8086634490d..0f42b6660a6 100644 --- a/libs/common/src/platform/services/state.service.ts +++ b/libs/common/src/platform/services/state.service.ts @@ -1048,23 +1048,6 @@ export class StateService< ); } - async getDecryptedPrivateKey(options?: StorageOptions): Promise { - return ( - await this.getAccount(this.reconcileOptions(options, await this.defaultInMemoryOptions())) - )?.keys?.privateKey.decrypted; - } - - async setDecryptedPrivateKey(value: Uint8Array, options?: StorageOptions): Promise { - const account = await this.getAccount( - this.reconcileOptions(options, await this.defaultInMemoryOptions()), - ); - account.keys.privateKey.decrypted = value; - await this.saveAccount( - account, - this.reconcileOptions(options, await this.defaultInMemoryOptions()), - ); - } - @withPrototypeForArrayMembers(SendView) async getDecryptedSends(options?: StorageOptions): Promise { return ( @@ -1752,24 +1735,6 @@ export class StateService< ); } - async getEncryptedPrivateKey(options?: StorageOptions): Promise { - const account = await this.getAccount( - this.reconcileOptions(options, await this.defaultOnDiskOptions()), - ); - return account?.keys?.privateKey?.encrypted; - } - - async setEncryptedPrivateKey(value: string, options?: StorageOptions): Promise { - const account = await this.getAccount( - this.reconcileOptions(options, await this.defaultOnDiskOptions()), - ); - account.keys.privateKey.encrypted = value; - await this.saveAccount( - account, - this.reconcileOptions(options, await this.defaultOnDiskOptions()), - ); - } - @withPrototypeForObjectValues(SendData) async getEncryptedSends(options?: StorageOptions): Promise<{ [id: string]: SendData }> { return ( @@ -2274,24 +2239,6 @@ export class StateService< ); } - async getPublicKey(options?: StorageOptions): Promise { - const keys = ( - await this.getAccount(this.reconcileOptions(options, await this.defaultInMemoryOptions())) - )?.keys; - return keys?.publicKey; - } - - async setPublicKey(value: Uint8Array, options?: StorageOptions): Promise { - const account = await this.getAccount( - this.reconcileOptions(options, await this.defaultInMemoryOptions()), - ); - account.keys.publicKey = value; - await this.saveAccount( - account, - this.reconcileOptions(options, await this.defaultInMemoryOptions()), - ); - } - async getRefreshToken(options?: StorageOptions): Promise { options = await this.getTimeoutBasedStorageOptions(options); return (await this.getAccount(options))?.tokens?.refreshToken; diff --git a/libs/common/src/platform/state/derive-definition.spec.ts b/libs/common/src/platform/state/derive-definition.spec.ts new file mode 100644 index 00000000000..5fc2bbf14e3 --- /dev/null +++ b/libs/common/src/platform/state/derive-definition.spec.ts @@ -0,0 +1,42 @@ +import { DeriveDefinition } from "./derive-definition"; +import { KeyDefinition } from "./key-definition"; +import { StateDefinition } from "./state-definition"; + +const derive: () => any = () => null; +const deserializer: any = (obj: any) => obj; + +const STATE_DEFINITION = new StateDefinition("test", "disk"); +const TEST_KEY = new KeyDefinition(STATE_DEFINITION, "test", { + deserializer, +}); +const TEST_DERIVE = new DeriveDefinition(STATE_DEFINITION, "test", { + derive, + deserializer, +}); + +describe("DeriveDefinition", () => { + describe("from", () => { + it("should create a new DeriveDefinition from a KeyDefinition", () => { + const result = DeriveDefinition.from(TEST_KEY, { + derive, + deserializer, + }); + + expect(result).toEqual(TEST_DERIVE); + }); + + it("should create a new DeriveDefinition from a DeriveDefinition", () => { + const result = DeriveDefinition.from([TEST_DERIVE, "newDerive"], { + derive, + deserializer, + }); + + expect(result).toEqual( + new DeriveDefinition(STATE_DEFINITION, "newDerive", { + derive, + deserializer, + }), + ); + }); + }); +}); diff --git a/libs/common/src/platform/state/derive-definition.ts b/libs/common/src/platform/state/derive-definition.ts index c164316be92..6c514f8869a 100644 --- a/libs/common/src/platform/state/derive-definition.ts +++ b/libs/common/src/platform/state/derive-definition.ts @@ -1,5 +1,6 @@ import { Jsonify } from "type-fest"; +import { UserId } from "../../types/guid"; import { DerivedStateDependencies, StorageKey } from "../../types/state"; import { KeyDefinition } from "./key-definition"; @@ -95,18 +96,60 @@ export class DeriveDefinition( - keyDefinition: KeyDefinition, + definition: + | KeyDefinition + | [DeriveDefinition, string], options: DeriveDefinitionOptions, ) { - return new DeriveDefinition(keyDefinition.stateDefinition, keyDefinition.key, options); + if (isKeyDefinition(definition)) { + return new DeriveDefinition(definition.stateDefinition, definition.key, options); + } else { + return new DeriveDefinition(definition[0].stateDefinition, definition[1], options); + } + } + + static fromWithUserId( + definition: + | KeyDefinition + | [DeriveDefinition, string], + options: DeriveDefinitionOptions<[UserId, TKeyDef], TTo, TDeps>, + ) { + if (isKeyDefinition(definition)) { + return new DeriveDefinition(definition.stateDefinition, definition.key, options); + } else { + return new DeriveDefinition(definition[0].stateDefinition, definition[1], options); + } } get derive() { @@ -137,3 +180,11 @@ export class DeriveDefinition + | [DeriveDefinition, string], +): definition is KeyDefinition { + return Object.prototype.hasOwnProperty.call(definition, "key"); +} diff --git a/libs/common/src/platform/state/state.provider.ts b/libs/common/src/platform/state/state.provider.ts index 3f8b623f012..69dac5bad67 100644 --- a/libs/common/src/platform/state/state.provider.ts +++ b/libs/common/src/platform/state/state.provider.ts @@ -49,7 +49,7 @@ export abstract class StateProvider { getGlobal: (keyDefinition: KeyDefinition) => GlobalState; getDerived: ( parentState$: Observable, - deriveDefinition: DeriveDefinition, + deriveDefinition: DeriveDefinition, dependencies: TDeps, ) => DerivedState; } diff --git a/libs/common/src/state-migrations/migrate.ts b/libs/common/src/state-migrations/migrate.ts index f43b64ab6d8..649fbc14a73 100644 --- a/libs/common/src/state-migrations/migrate.ts +++ b/libs/common/src/state-migrations/migrate.ts @@ -14,6 +14,7 @@ import { LastSyncMigrator } from "./migrations/16-move-last-sync-to-state-provid import { EnablePasskeysMigrator } from "./migrations/17-move-enable-passkeys-to-state-providers"; import { AutofillSettingsKeyMigrator } from "./migrations/18-move-autofill-settings-to-state-providers"; import { RequirePasswordOnStartMigrator } from "./migrations/19-migrate-require-password-on-start"; +import { PrivateKeyMigrator } from "./migrations/20-move-private-key-to-state-providers"; import { FixPremiumMigrator } from "./migrations/3-fix-premium"; import { RemoveEverBeenUnlockedMigrator } from "./migrations/4-remove-ever-been-unlocked"; import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys"; @@ -24,7 +25,7 @@ import { MoveBrowserSettingsToGlobal } from "./migrations/9-move-browser-setting import { MinVersionMigrator } from "./migrations/min-version"; export const MIN_VERSION = 2; -export const CURRENT_VERSION = 19; +export const CURRENT_VERSION = 20; export type MinVersion = typeof MIN_VERSION; export function createMigrationBuilder() { @@ -46,7 +47,8 @@ export function createMigrationBuilder() { .with(LastSyncMigrator, 15, 16) .with(EnablePasskeysMigrator, 16, 17) .with(AutofillSettingsKeyMigrator, 17, 18) - .with(RequirePasswordOnStartMigrator, 18, CURRENT_VERSION); + .with(RequirePasswordOnStartMigrator, 18, 19) + .with(PrivateKeyMigrator, 19, CURRENT_VERSION); } export async function currentVersion( diff --git a/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.spec.ts b/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.spec.ts new file mode 100644 index 00000000000..583b2c7aef5 --- /dev/null +++ b/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.spec.ts @@ -0,0 +1,127 @@ +import { MockProxy, any } from "jest-mock-extended"; + +import { MigrationHelper } from "../migration-helper"; +import { mockMigrationHelper } from "../migration-helper.spec"; + +import { PrivateKeyMigrator } from "./20-move-private-key-to-state-providers"; + +function exampleJSON() { + return { + global: { + otherStuff: "otherStuff1", + }, + authenticatedAccounts: ["user-1", "user-2", "user-3"], + "user-1": { + keys: { + privateKey: { + encrypted: "user-1-encrypted-private-key", + }, + otherStuff: "overStuff2", + }, + otherStuff: "otherStuff3", + }, + "user-2": { + keys: { + otherStuff: "otherStuff4", + }, + otherStuff: "otherStuff5", + }, + }; +} + +function rollbackJSON() { + return { + "user_user-1_crypto_privateKey": "encrypted-private-key", + "user_user-2_crypto_privateKey": null as any, + global: { + otherStuff: "otherStuff1", + }, + authenticatedAccounts: ["user-1", "user-2", "user-3"], + "user-1": { + keys: { + otherStuff: "overStuff2", + }, + otherStuff: "otherStuff3", + }, + "user-2": { + keys: { + otherStuff: "otherStuff4", + }, + otherStuff: "otherStuff5", + }, + }; +} + +describe("privateKeyMigrator", () => { + let helper: MockProxy; + let sut: PrivateKeyMigrator; + const keyDefinitionLike = { + key: "privateKey", + stateDefinition: { + name: "crypto", + }, + }; + + describe("migrate", () => { + beforeEach(() => { + helper = mockMigrationHelper(exampleJSON(), 19); + sut = new PrivateKeyMigrator(19, 20); + }); + + it("should remove privateKey from all accounts", async () => { + await sut.migrate(helper); + expect(helper.set).toHaveBeenCalledTimes(1); + expect(helper.set).toHaveBeenCalledWith("user-1", { + keys: { + otherStuff: "overStuff2", + }, + otherStuff: "otherStuff3", + }); + }); + + it("should set privateKey value for each account", async () => { + await sut.migrate(helper); + + expect(helper.setToUser).toHaveBeenCalledTimes(1); + expect(helper.setToUser).toHaveBeenCalledWith( + "user-1", + keyDefinitionLike, + "user-1-encrypted-private-key", + ); + }); + }); + + describe("rollback", () => { + beforeEach(() => { + helper = mockMigrationHelper(rollbackJSON(), 20); + sut = new PrivateKeyMigrator(19, 20); + }); + + it.each(["user-1", "user-2", "user-3"])("should null out new values %s", async (userId) => { + await sut.rollback(helper); + + expect(helper.setToUser).toHaveBeenCalledWith(userId, keyDefinitionLike, null); + }); + + it("should add explicit value back to accounts", async () => { + await sut.rollback(helper); + + expect(helper.set).toHaveBeenCalledTimes(1); + expect(helper.set).toHaveBeenCalledWith("user-1", { + keys: { + privateKey: { + encrypted: "encrypted-private-key", + }, + otherStuff: "overStuff2", + }, + otherStuff: "otherStuff3", + }); + }); + + it("should not try to restore values to missing accounts", async () => { + await sut.rollback(helper); + + expect(helper.set).not.toHaveBeenCalledWith("user-3", any()); + }); + }); +}); diff --git a/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.ts b/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.ts new file mode 100644 index 00000000000..267a4e3aa03 --- /dev/null +++ b/libs/common/src/state-migrations/migrations/20-move-private-key-to-state-providers.ts @@ -0,0 +1,53 @@ +import { KeyDefinitionLike, MigrationHelper } from "../migration-helper"; +import { Migrator } from "../migrator"; + +type ExpectedAccountType = { + keys?: { + privateKey?: { + encrypted?: string; // EncryptedString + }; + }; +}; + +const USER_ENCRYPTED_PRIVATE_KEY: KeyDefinitionLike = { + key: "privateKey", + stateDefinition: { + name: "crypto", + }, +}; + +export class PrivateKeyMigrator extends Migrator<19, 20> { + async migrate(helper: MigrationHelper): Promise { + const accounts = await helper.getAccounts(); + async function migrateAccount(userId: string, account: ExpectedAccountType): Promise { + const value = account?.keys?.privateKey?.encrypted; + if (value != null) { + await helper.setToUser(userId, USER_ENCRYPTED_PRIVATE_KEY, value); + delete account.keys.privateKey; + await helper.set(userId, account); + } + } + + await Promise.all([...accounts.map(({ userId, account }) => migrateAccount(userId, account))]); + } + async rollback(helper: MigrationHelper): Promise { + const accounts = await helper.getAccounts(); + async function rollbackAccount(userId: string, account: ExpectedAccountType): Promise { + const value = await helper.getFromUser>( + userId, + USER_ENCRYPTED_PRIVATE_KEY, + ); + if (account && value) { + account.keys = Object.assign(account.keys ?? {}, { + privateKey: { + encrypted: value, + }, + }); + await helper.set(userId, account); + } + await helper.setToUser(userId, USER_ENCRYPTED_PRIVATE_KEY, null); + } + + await Promise.all([...accounts.map(({ userId, account }) => rollbackAccount(userId, account))]); + } +} diff --git a/libs/common/src/types/key.ts b/libs/common/src/types/key.ts index 3b2448224e2..c9fd6975960 100644 --- a/libs/common/src/types/key.ts +++ b/libs/common/src/types/key.ts @@ -14,3 +14,4 @@ export type CipherKey = Opaque; // asymmetric keys export type UserPrivateKey = Opaque; +export type UserPublicKey = Opaque;